简体   繁体   中英

Calling a function (ex. namespace.show) by name

I want to call a function with a namespace based on its name.

Perhaps some background: What I want is, dynamically bind pages via $.mobile.loadPage(inStrUrl, { showLoadMsg: false }); and then, based on the current page, invoke a function within a loaded page. For example: each page has a showFilter function, the Event is attached to a main.html - page which should call the matching function in the current page.

I also tried some solutions, with jquery too, but nothing works for me.

This is my function code:

function namespace() { }
namespace.showFilter = function () {
        alert("Test");
    }

And want to "invoke" or "call" it via its name. This is what i tried at least.

$(document).ready(function() {
var fn = window["namespace.showFilter"];
fn();
});

I get error TypeError: fn is not a function

Here is a fiddle http://jsfiddle.net/xBCes/1/

You can call it in the following way:

$(document).ready(function() {
    window["namespace"]["showFilter"]();
});

or

$(document).ready(function() {
    window["namespace"].showFilter();
});

or

$(document).ready(function() {
    window.namespace.showFilter();
});

I found that I had to manually set it to window.

window.namespace = function() { }
window.namespace.showFilter = function () {
            alert("Test");
};

$(document).ready(function() {
    var fn = window["namespace"]["showFilter"];
    fn();
});

http://jsfiddle.net/xBCes/4/

Like this:

$(function() {
    window.namespace.showFilter();
});

PS I shortened the $(document).ready(...)

function namespace() {}
    namespace.showFilter = function () {
            alert("Test");
        }


$(document).ready(function() {
    var fn = namespace.showFilter();
    fn();
});

http://jsfiddle.net/xBCes/3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM