Created
February 25, 2014 02:14
-
-
Save chemdemo/9201391 to your computer and use it in GitHub Desktop.
simple event dispatcher.
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
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