Skip to content

Instantly share code, notes, and snippets.

@gvn
Created June 19, 2012 23:53
Show Gist options
  • Save gvn/2957212 to your computer and use it in GitHub Desktop.
Save gvn/2957212 to your computer and use it in GitHub Desktop.
event binding pattern
window.Component = {
init: function () {
var self = this;
self.events.parent = self;
self.callbacks = {};
},
events: {
actionHappened: function (event) {
var self = this.parent;
self.runCallbacks('actionHappened', event);
}
},
action: function () {
var self = this;
self.events.actionHappened({metadata: 'More event info...'});
},
bind: function (eventType, callback, scope) {
var self = this;
if (typeof self.callbacks[eventType] === 'undefined') {
self.callbacks[eventType] = [];
}
self.callbacks[eventType].push({
callback: callback,
scope: scope
});
},
unbind: function (eventType) {
var self = this;
self.callbacks[eventType] = [];
},
runCallbacks: function (eventType, eventData) {
var self = this,
i,
ii;
if (typeof self.callbacks[eventType] !== 'undefined') {
for (i = 0, ii = self.callbacks[eventType].length; i < ii; i++) {
self.callbacks[eventType][i].callback.call(self.callbacks[eventType][i].scope || self, eventData);
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment