Skip to content

Instantly share code, notes, and snippets.

@chemdemo
Created February 25, 2014 02:14
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 chemdemo/9201391 to your computer and use it in GitHub Desktop.
Save chemdemo/9201391 to your computer and use it in GitHub Desktop.
simple event dispatcher.
var dispatcher = function() {
var pools = {};
// {
// 'foo': [fn1, fn2],
// 'bar': [fn3, fn4]
// }
return {
on: function(action, handle) {
var actions = pools[action] || (pools[action] = []);
actions.push(handle);
},
trigger: function(action, data) {
var actions = action.split(/\W+/);
var handles;
actions.forEach(function(action) {
handles = pools[action];
handles.forEach(function(handle) {
'function' === typeof handle && handle.call(data.$self || null, data);
});
});
}
}
}();
$(document).on('click', '.event-delegated', function(e) {
var $self = $(this);
var action = $self.data('action-name');
dispatcher.trigger(action, {
$self: $self,
$event: e,
data: $self.data('action-data')
});
});
// html
// <button type="button" class="event-delegated" action-name="foo" action-data="{foo: bar}">foo</button>
// <a href="##" class="event-delegated" action-name="foo" action-data="{foo: baz}">baz</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment