Javascript链接从回调返回这个

javascript chainning return this from callback

本文关键字:返回 回调 链接 Javascript      更新时间:2023-09-26

我试图从回调中获得一个返回值,但我总是得到未定义。

这里是剪短的

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

变量1现在是未定义的,如果我使用fadeIn回调…如果我没有在回调中使用fadeIn它会返回obj

有人知道为什么吗?

@Felix Kling说的是正确的,您没有返回任何东西。如果你想返回itsMe,你需要做:

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

应该足够了。

如果你想在淡出结束时获得对itsMe的引用,你需要传递你自己的回调:

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);
});

如果你想有一个链模式,它将在淡出完成时执行链中的下一个函数,你需要传递的不是对this的引用,而是一个可以将命令排队的对象,按顺序执行每个命令。

您需要在create()函数中返回对象,它目前没有返回任何内容:

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
},