0

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

2
  • is this what you want [link] jsfiddle.net/alexk/36Ds5 it uses a pass as function name string Commented Jun 1, 2012 at 16:44
  • @shareef Sort of, but I wouldn't know that the namespace would be MyNameSpace, that's part of the string. So it would need to be able to call 'product.addimage' and 'somethingelse.dosomething' in the same code Commented Jun 1, 2012 at 17:01

1 Answer 1

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`
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.