javascript chainning return this from callback

2019-08-25 01:10发布

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?

2条回答
男人必须洒脱
2楼-- · 2019-08-25 01:56

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.

查看更多
放我归山
3楼-- · 2019-08-25 01:58

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
},
查看更多
登录 后发表回答