Last active
September 11, 2022 08:55
-
-
Save ericelliott/06b434591f8d80c57cf2bff20683e0fd to your computer and use it in GitHub Desktop.
Functional mixin example
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
import Events from 'eventemitter3'; | |
const rawMixin = function () { | |
const attrs = {}; | |
return Object.assign(this, { | |
set (name, value) { | |
attrs[name] = value; | |
this.emit('change', { | |
prop: name, | |
value: value | |
}); | |
}, | |
get (name) { | |
return attrs[name]; | |
} | |
}, Events.prototype); | |
}; | |
const mixinModel = (target) => rawMixin.call(target); | |
const george = { name: 'george' }; | |
const model = mixinModel(george); | |
model.on('change', data => console.log(data)); | |
model.set('name', 'Sam'); | |
/* | |
{ | |
prop: 'name', | |
value: 'Sam' | |
} | |
*/ |
Why you’re using “this” keyword to pass object that should be extended?
What extra benefits does this approach have comparing to using argument for the same purpose?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
there is a minor typo a :27
consle
instead ofconsole