Call function under object from string
        Posted  
        
            by 
                sam
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by sam
        
        
        
        Published on 2012-06-01T16:37:14Z
        Indexed on 
            2012/06/01
            16:40 UTC
        
        
        Read the original article
        Hit count: 428
        
JavaScript
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
© Stack Overflow or respective owner