up
This commit is contained in:
parent
ab9ab64bd5
commit
97c8f22bbb
289 changed files with 195 additions and 172 deletions
43
1-js/07-object-oriented-programming/13-mixins/head.html
Normal file
43
1-js/07-object-oriented-programming/13-mixins/head.html
Normal file
|
@ -0,0 +1,43 @@
|
|||
<script>
|
||||
let eventMixin = {
|
||||
|
||||
/**
|
||||
* Subscribe to event, usage:
|
||||
* menu.on('select', function(item) { ... }
|
||||
*/
|
||||
on(eventName, handler) {
|
||||
if (!this._eventHandlers) this._eventHandlers = {};
|
||||
if (!this._eventHandlers[eventName]) {
|
||||
this._eventHandlers[eventName] = [];
|
||||
}
|
||||
this._eventHandlers[eventName].push(handler);
|
||||
},
|
||||
|
||||
/**
|
||||
* Cancel the subscription, usage:
|
||||
* menu.off('select', handler)
|
||||
*/
|
||||
off(eventName, handler) {
|
||||
let handlers = this._eventHandlers && this._eventHandlers[eventName];
|
||||
if (!handlers) return;
|
||||
for(let i = 0; i < handlers.length; i++) {
|
||||
if (handlers[i] == handler) {
|
||||
handlers.splice(i--, 1);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Generate the event and attach the data to it
|
||||
* this.trigger('select', data1, data2);
|
||||
*/
|
||||
trigger(eventName, ...args) {
|
||||
if (!this._eventHandlers || !this._eventHandlers[eventName]) {
|
||||
return; // no handlers for that event name
|
||||
}
|
||||
|
||||
// call the handlers
|
||||
this._eventHandlers[eventName].forEach(handler => handler.apply(this, args));
|
||||
}
|
||||
};
|
||||
</script>
|
Loading…
Add table
Add a link
Reference in a new issue