A deferred factory object
Defactor allows creating deferred objects with a many-to-many relationship between queues and triggers. By creating this type of event map there shouldn't be a need for callback insanity. The idea is to create new deferreds for different call types, then return new instances. By doing this the end user's API can be fully chained. Here's an example:
// generate a new deferred object with custom event triggers and function queuesvar defer = defactoradd 'resolve' 'done always'add 'reject' 'fail always'create;// OR use the alternate syntax by passing an object// (note: this will add all triggers/queues then create() when complete)var defer = defactorresolve : 'done always'reject : 'fail always';// create an instance of the new deferredvar myDef = ; // or just `defer()`// queue up functions to completemyDefdoneconsole.log 'done:' + arg + ':' + thisctx ;failconsole.log 'fail' ;alwaysconsole.log 'always' ;;myDefresolve 'now'ctx : 'here'; // LOG: "done:now:here"; "always"
defactor( [clear],[map] ): initialize new defactor object. If
clear === true then default behavior is to clear queue after trigger.
map will accept an object of triggers : queues then create the deferred automatically.
.add( trigger, queue ): adds a new trigger/queue to the stack.
queue can be a space separated string, or an array.
.create(): generates new deferred from the defactor object.
Queues can be passed context and/or an array of arguments
All generated deferreds have a
promise() method that will return a promise object
Events will be cleared after triggering if
true is passed when instantiating the deferred
add()can be a function, which will execute when called and pass any arguments. Example:
var onEvent = defactoradd 'trigger' 'debug'add 'trigger' 'ajax' // make an ajax callvar ctx = thiscall = $ajax opts ;return ctx;;return call;;var e = true// ajax returns a new deferred contextajax// optionssuccess fn // if call succeedsfail fn // if call failsend // return to previous contextdebug// log some stuff;etrigger;