Skip to main content
2 of 4
added 6 characters in body
Larry Battle
  • 2.2k
  • 11
  • 19

##Tips: #1) Returning this from a function of an object instance allows for the method to become chainable.

Example:

var File = function(){
    this.readCallCount = 0;
    return this;
};
File.prototype.readLine = function(){
    this.readCallCount++;
    console.log( "read line: " + this.readCallCount );
    return this;
};
var fileA = new File();
fileA.readLine().readLine().readLine();
/*
output:
read line: 1
read line: 2
read line: 3
*/

#2) The passed parameters from deferred.resolve() are saved until deferred.resolve() is invoked again. Therefore the callbacks stored from deferred.done() will be passed the same values from the last call from deferred.resolve().

Example:

var arr = [];
function log(str){
    return arr.push( str );
}
function fn1(time) {
  return log( "fn1 called at " + time );
}
function fn2(time) {
  return log( "fn2 called at " + time );
}
var dfd = $.Deferred();
dfd.done(fn1);
dfd.resolve( +(new Date()) );

setTimeout(function(){
    dfd.done(fn2);
    console.log( arr.join( ", " ) );
}, 2000);
/*
 outputs after 2 seconds
 fn1 called at 1348177948625, fn2 called at 1348177948625
*/

Different results can be provided if a function or object is passed to deferred.resolve().

Example:

var arr = [];
function log(str){
    return arr.push( str );
}
function fn1(getTimeFunc) {
  return log( "fn1 called at " + getTimeFunc() );
}
function fn2( getTimeFunc ) {
  return log( "fn2 called at " +  getTimeFunc() );
}
var dfd = $.Deferred();
dfd.done(fn1);
dfd.resolve(function(){
    return +(new Date()) 
});

setTimeout(function(){
    dfd.done(fn2);
    console.log( arr.join( ", " ) );
}, 2000);
/*
output after 2 seconds
fn1 called at 1348178107859, fn2 called at 1348178109860
*/

##Final Code:

This might work. Instead of extending the deferred object to include a read method, I opted to return an plain object.

Note: My code is assuming that libraryCall() and fileEntry.getText() return a deferred.promise() or deferred object.

Code:

var FileEntryObj = function(){
    this.libraryCallObj = libraryCall();
};
FileEntryObj.prototype.read = function(fn){
    this.libraryCallObj.done( function( fileEntry ){
        return fileEntry.getText().done( fn );
    });
    return this;
};
var getFileEntry = function(){
    return new FileEntryObj();
};

Usage:

getFileEntry().read(function (text) {
    console.log("reading content:" + text);
}).read(function (text) {
    console.log("reading content again: " + text);
});
Larry Battle
  • 2.2k
  • 11
  • 19