Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Last active September 11, 2022 08:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ericelliott/06b434591f8d80c57cf2bff20683e0fd to your computer and use it in GitHub Desktop.
Save ericelliott/06b434591f8d80c57cf2bff20683e0fd to your computer and use it in GitHub Desktop.
Functional mixin example
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'
}
*/
@alvaropinot
Copy link

there is a minor typo a :27 consle instead of console

@surgeboris
Copy link

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