I want to implement traits like PHP in AngularJs. What is the best solution to do it?
1 Answer
I found a simple way to do it:
First, create a file named traits.js
angular.module('myApp')
.factory('Traits', function() {
return {
apply: function (_class, _trait) {
_.each(_trait, function (method, name) {
_class.prototype[name] = method;
});
}
}
});
Then, create your trait file my-trait.js
angular.module('myApp')
.factory('MyTrait', function() {
return {
someMethod: function (param) {
//
},
anotherMethod: function (param) {
//
}
}
});
And then use the trait like this:
angular.module('myApp')
.factory('MyResource', function($resource, Traits, MyTrait) {
var resource = $resource();
Traits.apply(resource, MyTrait);
return resource;
});
3 Comments
Peter Seliger
1/3 ... This very much looks like "timbering" object based mixins (merely kind of an config object with just methods) into the angular environment. This approach also looks like it is limiting one to just enhancing a constructor functions prototype object. Thus instead of writing
_.each(_trait, function (method, name) {_class.prototype[name] = method;}); something like Object.assign(_class.prototype, _trait) shows the true nature of this approach. ...Peter Seliger
2/3 ... Besides that, Traits are distinct from Mixins in a way that the former provides operations/functionality for resolving (naming) conflicts at apply/composition time whereas the latter does overwrite whatever was there before. A good trait implementation in JavaScript is agnostic to libraries and frameworks. Thus it ideally was implemented as domain specific language that would provide a good variety of tools for object composition and maybe even state handling. ...
Peter Seliger
3/3 ... of course your solution shows one possible approach of how to implement kind of Mixin based composition via the usage of angular modules. Of course this also is far away from what PHP provides.