Last active
December 20, 2015 23:39
-
-
Save dmi3y/6213987 to your computer and use it in GitHub Desktop.
Async publisher subscriber for YUI3, intern solution cause weird behavior of custom events when fire them globally. Sandbox/playground http://jsbin.com/ibubaq/10/edit, SO http://stackoverflow.com/questions/18158657/yui3-custom-async-events-not-working-on-y-global
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
YUI.add('async-pubsub', function(Y) { | |
'use strict'; | |
if (!YUI.asyncPubSub) { | |
YUI.namespace('asyncPubSub'); | |
YUI.asyncPubSub = (function() { | |
var eventsFired = {}, eventsSubscribed = {}; | |
function doPublishFor(eventName) { | |
var subscribers = eventsSubscribed[eventName], | |
len, it; | |
if (subscribers) { | |
len = subscribers.length; | |
for (; --len > -1;) { | |
it = subscribers[len]; | |
if (!it.called) { | |
it.callback.call(); | |
it.called = true; | |
} | |
} | |
} | |
} | |
return { | |
publish: function(eventName, options) { | |
eventsFired[eventName] = options || {}; | |
doPublishFor(eventName); | |
}, | |
subscribe: function(eventName, callback) { | |
var slot = {}; | |
slot.callback = callback || function() {}; | |
slot.called = false; | |
eventsSubscribed[eventName] = eventsSubscribed[eventName] || []; | |
eventsSubscribed[eventName].push(slot); | |
if (eventsFired[eventName]) { | |
doPublishFor(eventName); | |
} | |
}, | |
/** | |
* Cleanup everything, experemental method for testing purposes, use with caution | |
* | |
* @param {str} eventName | |
*/ | |
detach: function(eventName) { | |
if (eventName) { | |
delete eventsFired[eventName]; | |
delete eventsSubscribed[eventName]; | |
} else { | |
eventsFired = {}; | |
eventsSubscribed = {}; | |
} | |
} | |
}; | |
})(); | |
} | |
Y.namespace('asyncPubSub'); | |
Y.asyncPubSub = YUI.asyncPubSub; | |
}, '1.0.1', { | |
requires: [] | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment