Chin
Chin

Reputation: 12712

Calling Method represented by string

I am being passed a string similar to below.

"Users_Controller.login"

"Users_Controller" represents the object below. And "login" a method within it.

var Users_Controller = ( function () {
return{

  login : function(vo, callback)
   {......}

 }
 })();

Given only the string as a pointer,is it possible call the method?

Upvotes: 0

Views: 49

Answers (2)

Jules
Jules

Reputation: 1423

Something like this?

var Users_Controller = (function () {
    return {

        login: function (name) {
            alert("hello " + name);
        },
        logout: function (name) { alert("goodbye "+name); }

    }
})();


var methods = {};

for (method in Users_Controller) {
    methods["Users_Controller." + method] = Users_Controller[method];
}

methods["Users_Controller.login"]('john');
methods["Users_Controller.logout"]('john');

Upvotes: 1

Digital Plane
Digital Plane

Reputation: 38264

You can use this function:

function getPropertyFromString(str, start) {
    str = str.split(".");
    var prop = start || window;
    for (var i = 0; i < str.length; i++) {
        if(prop == undefined)
          return prop;
        else
          prop = prop[str[i]];
    }
    return prop;
}
getPropertyFromString("Users_Controller.login");

However, this does not allow bracket syntax.

Upvotes: 1

Related Questions