Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Javascript function from a hash value with namespaces

I currently have this code to call a function from a hash value on page load:

$(function() {
    var hash = window.location.hash.substring(1);
    window[hash]();
});

This works great.

However, my Javascript in namespaced like so:

    var help = {
            faq: function () {
                //do stuff
            },

            newFeatures: function () {
                //do stuff
            }
    }

My function that I listed up top does not work for namespaced javascript. I've tried manually adding the namespace to the front (so var hash = "help." + window.location.hash.substring(1);) but that did not work.

How can I navigate around this issue without removing my Javascript from a namespace?

like image 715
Hanna Avatar asked Aug 08 '26 19:08

Hanna


2 Answers

This should work:

$(function() {
    var hash = window.location.hash.substring(1);
    window.help[hash]();
});

In JavaScript dot notation and square brackets are interchangeable, as long as the key is a valid JavaScript identifier. (Otherwise, you have to use square brackets.)

So you could also do this (although dot notation is more readable):

$(function() {
    var hash = window.location.hash.substring(1);
    window["help"][hash]();
});
like image 146
Bennor McCarthy Avatar answered Aug 11 '26 08:08

Bennor McCarthy


I am using a similar method where I store object values in a hash.

My technique:

  • use a dot in the hash to show the hierarchy - in your case: #help.faq
  • run a script to convert the dot notation and retrieve the actual value

Live demo: http://jsfiddle.net/Kn4w2/1/

Code sample:

var hashArray=hash.split("."),
    myMethod=window;
for (var i=0;i<hashArray.length;i++){
        myMethod=myMethod[hashArray[i]];
}

The only constraint is that of course your method names should not contain a dot.

like image 43
Christophe Avatar answered Aug 11 '26 09:08

Christophe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!