Search code examples
javascriptcallbackreturnchaining

javascript chainning return this from callback


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?


Solution

  • 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.