3

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?

Hanna
  • 10,315
  • 11
  • 56
  • 89

3 Answers3

4

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]();
});
Bennor McCarthy
  • 11,415
  • 1
  • 49
  • 51
1

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.

Christophe
  • 27,383
  • 28
  • 97
  • 140
  • What I really like about this solution is that it easily allows for multiple namespaces and I can reuse the same functionality. I appreciate your input. Thanks! – Hanna Mar 01 '13 at 20:16
  • Absolutely! I actually use it for general cases with more than two levels (for example #help.faq.question1), but then the code becomes more complicated as you need to add validation steps. – Christophe Mar 01 '13 at 20:48
  • I'm actually considering turning a web project into a single-page app and a set-up like this would make mapping to controllers and actions pretty darn easy with javascript and ajax. – Hanna Mar 02 '13 at 00:59
-2

I'm not really a fan, but 'eval' might work:

eval(hash + "()");

Example: http://jsfiddle.net/pGktd/

opznhaarlems
  • 337
  • 2
  • 9