This might work. Instead of extending the deferred object to include a read method, I opted to return an plain 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);
});
Tips##Tips:
#1)
Returning this
from a function of an object instance allows for the method to become chainable.
ButDifferent results can be provided if a function or object is passed to deferred.resolve()
, then you can get different results from the parameter.
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);
});