Blank
Blank

Reputation: 4695

Call function under object from string

I have a script which creates a drag-and-drop uploader on the page from a div. My DIV will look something like

<div class="well uploader"
    data-type="image"
    data-callback="product.addimage"
    data-multi="1"></div>

Then I'll have a function something like

var product = new function(){
    /* Some random stuff */
    this.addimage = function(image){
        alert('W00T! I HAZ AN IMAGE!');
    }
    /* More random stuff */
}

When the upload is complete, I need to call the function in data-callback (In this example, product.addimage). I know with global functions you can just do window[callback]() but I'm not sure the best way to do this with functions under objects.

My first thought was to do something like*

var obj = window;
var parts = callback.split('.');
for(part in parts){
    obj = obj[parts[part]];
}
obj();

but that seems a bit dirty, is there a better way without using eval because eval is evil?

I haven't tested this so I have no idea if it will work

Upvotes: 0

Views: 85

Answers (1)

Thomas Eding
Thomas Eding

Reputation: 1

Yeah, it would work, though I would code it as such:

function followPropPath (obj, propPath) {
    var pathParts = propPath.split(".");
    for (var i = 0; i < pathParts.length; ++i) {
        obj = obj[pathParts[i]];
    }
    return obj;
}

var obj = { x: { y: { z: { f: function() { alert(this); } } } } };

followPropPath(obj, "x.y.z")["f"](); // `this` is `z`
followPropPath(obj, "x.y.z.f")(); // `this` is `window`

Upvotes: 1

Related Questions