var dfd = $.Deferred();
if (something) {
dfd.resolve();
} else {
dfd.reject();
}
Well no more! Enter "cond".
$.Deferred = (function (baseDeferred) {
var slicer = [].slice;
var cond = function (truthy) {
return this[truthy ? 'resolve' : 'reject'].apply(this, slicer.call(arguments, 1));
};
return function() {
var dfd = baseDeferred.apply(this, arguments);
dfd.cond = cond;
return dfd;
};
})($.Deferred);
Unfortunately, as shown by the relative complexity of this code, jQuery doesn't actually use a prototype for the deferred objects it creates, so you have to 'duck punch' the feature in.
Usage (after including the previous script somewhere):
var dfd = $.Deferred();
dfd.cond(true, { some: 'data' });
dfd.then(function (res) {
console.log(res);
});
1 comment:
Post a Comment