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?
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]();
});
I am using a similar method where I store object values in a hash.
My technique:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With