Skip to content

Instantly share code, notes, and snippets.

@lsmith
Created March 7, 2013 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lsmith/5106331 to your computer and use it in GitHub Desktop.
Save lsmith/5106331 to your computer and use it in GitHub Desktop.
Publish a custom event that respects promises returned from the defaultFn.
function promiseFire(data) {
var event = this,
target = this.host;
event._firing = event._firing.then(function () {
return new Y.Promise(function (resolve, reject) {
// Execute on() subscribers
var e = Y.merge({
preventDefault: function () {
this.prevented = true;
reject(this);
}
}, data),
subs = event._subscribers,
i, len;
for (i = 0, len = subs.length; i < len; ++i) {
// TODO: try/catch?
subs[i].fn.call(subs[i].context || target, e);
}
if (e.prevented) {
reject(event.type + " event prevented");
} else {
resolve(e);
}
}).then(function (e) {
// Default function
var promise = event.defaultFn.call(target, e);
if (promise === false || e.stopped === 2) {
throw new Error("event stopped");
}
// Return promise to postpone after() subs or return the event to
// immediately resolve.
return promise || e
}).then(function (e) {
// Execute after() subscribers
// This purposely allows after subscribers to be added during the
// lifecycle of the event firing.
var subs = event._afters,
i, len;
for (i = 0, len = subs.length; i < len; ++i) {
subs[i].fn.call(subs[i].context || target, e);
}
return e;
});
// Catch errors/preventions and reset the promise state to fulfilled for
// the next call to fire();
}).then(null, function () { return null; });
};
// Wrap the current publish implementation on EventTarget
Y.EventTarget.prototype.publish = (function (original) {
var event = original.apply(this, arguments);
if (event.promises) {
// Add promise compatible fire method
event._firing = new Y.Promise(function (resolve) { resolve(); });
event.fire = promiseFire;
}
return event;
})(Y.EventTarget.prototype.publish);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment