Allison L Allison L - 7 months ago 10
PHP Question

Is there a JavaScript DEFINE directive equivalent?

Inside a php file I have a script such as this snippet:

<script>
$(function(){
$("#tabs_<?php echo $keyCode ?>").tabs();

var x = document.getElementById("bkhmode_<?php echo $keyCode ?>");
var mode = x.value;
setcont_<?php echo $keyCode ?>(mode);
});
</script>


I want to remove this piece of code along with many other lines like it into a separate JS file to take advantage of caching BUT I have been unable to find the equivalent of a DEFINE command to allow me to replace the php echo.

I would like to

DEFINE KEY_CODE = 'somevalue';


then the snippet would look something like this:

<script>
$(function(){
$("#tabs_KEY_CODE").tabs();
var x = document.getElementById("bkhmode_KEY_CODE");
var mode = x.value;
setcont_KEY_CODE(mode);
});
</script>


Most languages allow for this but I have been unable to find anything equivalent in JavaScript. Any suggestions?

Answer

You may set variables to the global window namespace, although it is considered bad practice as it can interfere with other programs, so be careful.

window.KEY_CODE = 'somevalue';

$(function() {
    $("#tabs_" + window.KEY_CODE); // Will escape local scope.
});

That should work, although it's common practice to do this with an IIFE.

(function(window, document, $, undefined) {
    $("#tabs_" + window.KEY_CODE); // Will escape local scope.
})(window, window.document, window.jQuery);

That helps resolve a lot of namespace issues because they're explicitly defined in the local scope.


You can also use global variables to run a function. If your function is declared outside of an IIFE (i.e. you've just run it in a global namespace), it's appended to the window element as well. For instance, these are equivalents.

function foo(a)
{
    console.log("foo" + a);
}

foo("bar"); // prints "foobar"
window.foo("bar2"); // prints "foobar2"
window['foo']("bar3"); // prints "foobar3"

This is because the browser will assume you're calling window.foo if the local variable foo is undefined. window['foo'] is an identical way of calling window.foo; it accesses the window object, but using a string. So, with that in mind, we can accomplish your variable function call.

window.KEY_CODE = 'somevalue';

window.func_somevalue = function(a) {
    console.log("somevalue = " + a);
};

window.func_othervalue = function(a) {
    console.log("othervalue = " + a);
}

// prints "somevalue = Hello."
window['func_' + window.KEY_CODE]("Hello.");

You can do this with other objects.

window.KEY_CODE = 'somevalue';

(function(window, document, $, undefined) {
    $("#tabs_" + window.KEY_CODE); // Will escape local scope.

    var keys = {
        'somevalue' : function(a) { console.log(a); },
        'othervalue' : function() { console.log('other'); }
    };

    keys[window.KEY_CODE]("Hello.");
})(window, window.document, window.jQuery);
Comments