Last active
August 29, 2015 14:02
-
-
Save tomchentw/6c6b0a3e07a2a33aaae0 to your computer and use it in GitHub Desktop.
Mixin include that would respond to changes
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
function mixinChanged (changes) { | |
changes.forEach(function (change) { | |
switch (change.type) { | |
case "add": | |
case "update": | |
this[change.name] = change.object[change.name]; | |
break; | |
case "delete": | |
delete this[name]; | |
break; | |
} | |
}, this/* .prototype */); | |
}; | |
Object.defineProperty(Object.getPrototypeOf(Function), "include", { | |
value: function (mixin) { | |
while(mixin) { | |
for (name in mixin) { | |
this.prototype[name] = mixin[name]; | |
} | |
Object.observe(mixin, mixinChanged.bind(this.prototype)); | |
mixin = mixin.ClassMethods; | |
} | |
} | |
}); | |
var User = function (it) { this._name = it; }; | |
var HasSearch = { | |
ClassMethods: { | |
search: function () { return [new User("Tom")]; } | |
}, | |
name: function () { return this._name; } | |
}; | |
User.include(HasSearch); | |
User.search()[0].name(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment