Nikolay Dyankov
Nikolay Dyankov

Reputation: 7234

How can I reference a non-global function with window[functionName]?

I'm making something like a framework for JS. I want the users to be able to add functions to a specific action, just like in wordpress plugins:

add_action("wp_head", "functionName");

I looked at other questions, and the most appreciated answer was

window['functionName']

But how do I do it when the function "functionName" is not global, but sits within $(document).ready({}); for example? It throws an error Uncaught TypeError: Cannot call method 'call' of undefined

There is one more option, that is to pass the user's function as an argument to add_action (if we suppose that my function will be named add_action as well):

add_action("some_event", functionName);
// in the framework's JS file:
function add_action(event, fn) {
    fn();
}

But I have a hunch that this will be inefficient as hell and a wrong way to do it.

Upvotes: 1

Views: 395

Answers (4)

icktoofay
icktoofay

Reputation: 129001

The last way — passing in the function — is actually the best way to do it. It is neither inefficient nor wrong.

Upvotes: 1

jfriend00
jfriend00

Reputation: 707396

You can put these functions on your own object and use it inside the document.ready function:

$(document).ready(function() {
    var fns = {};
    fns.myFunc = function() {};

    // execute the function by name
    var fnName = "myFunc";
    fns[fnName]();
});

Or, if you want to reference it outside of the document.ready() scope, you can put it on the window object and make it your own namespaced global:

$(document).ready(function() {
    window.myFunctionTable = {};
    window.myFunctionTable.myFunc = function() {};
});

// execute the function by name
var fnName = "myFunc";
window.myFunctionTable[fnName]();

Upvotes: 1

Kevin Ennis
Kevin Ennis

Reputation: 14466

Ideally, you really want to namespace your app -- so you have something like

window.MY_APP = {...};

or whatever, and then you add all your methods/properties/modules for the whole framework to that namespace.

Upvotes: 0

Pointy
Pointy

Reputation: 413737

You can't. However, if you absolutely must have a global function, you can tack it onto the jQuery object:

$.yourSpecialFunction = function() {
  // ...
};

Worse, you could add it to window:

window.yourSpecialFunction = function() {
  // ...
}

But there's really no reason to do that.

Upvotes: 0

Related Questions