javascript chainning return this from callback

三世轮回 提交于 2019-12-24 22:08:04

问题


i've tried to get a return this from a callback, but i always get undefined.

here is the snipped

create: function(currentView, data){
    var itsMe = this; 
    this.thumbsWrapper = this.templates.wrapper().hide();
    currentView.append(this.thumbsWrapper);
    this.thumbsWrapper.fadeIn("fast", function(){
        return itsMe;                                                 
    });
},

var l = list().create(currentView); //need teh return that i can use chaining

the var l is now undefined, if i use the fadeIn with a callback... if i dont use fadeIn with the callback it returns the obj

anyone an idea why?


回答1:


What @Felix Kling say is correct, you are not returning anything. If you want to return itsMe you will need to do:

create: function(currentView, data){
    var itsMe = this; 
    this.thumbsWrapper = this.templates.wrapper().hide();
    currentView.append(this.thumbsWrapper);
    this.thumbsWrapper.fadeIn("fast");
    return itsMe;    
}

Which should suffice if you want chaining.

If you want to get a reference to itsMe when the fadeout is finished, you will need to pass your own callback:

create: function(currentView, data, callback){
    var itsMe = this; 
    this.thumbsWrapper = this.templates.wrapper().hide();
    currentView.append(this.thumbsWrapper);
    this.thumbsWrapper.fadeIn("fast", function(){ 
        callback(itsMe);
    });  
}


list().create(function (that) {
    console.log("fade out complete");
    console.log("itsMe is", that);
});

And if you want to have a chaining pattern, which will execute the next function in the chain when fadeout is finished, you will need to pass not a reference to this but an object which can queue up commands, implement each command sequentially.




回答2:


You need to return the object in the create() function, it is currently not returning anything:

create: function(currentView, data){
    var itsMe = this; 
    this.thumbsWrapper = this.templates.wrapper().hide();
    currentView.append(this.thumbsWrapper);
    this.thumbsWrapper.fadeIn("fast", function(){
        return itsMe;  //<--- this isn't going anywhere because you don't capture it                                               
    });
    return itsMe; //<------ return the object
},


来源:https://stackoverflow.com/questions/14258744/javascript-chainning-return-this-from-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!