In the standard ember mixin example we add instance methods/properties: http://emberjs.com/api/classes/Ember.Mixin.html
With reopenClass we can add class methods (static methods), giving us something like:
UninstantiatedClass.findAll()
Can I create a mixin that adds class methods?
Yes you can!
Simply provide the mixin during a reopenClass invocation:
// The mixin itself
FooMixin = Em.Mixin.create({
...
});
// Mix in at the instance level
BarClass = Em.Object.extend(FooMixin, {
...
});
// Mix in at the class level
BarClass.reopenClass(FooMixin, {
...
});
I stumbled across this problem as well, and discovered this being done in the Discourse project.
Hope this helps!
First of all, I'm still learning EmberJS. :)
I had the same problem: how to add common class methods to a class.
My understanding is that you can't do it using Mixins (Warning: I might be wrong) but you can do it using a plain subclass.
Look at this jsbin. App.Soldier is a subclass of App.Person which contains instance and class methods. These are available to App.Soldier.
If you type these commands in the console:
x = App.Soldier.create();
x.hello(); // => "hello world!"
x.fire(); // => "Laser gun, pew! pew!"
App.Soldier.identifyYourself(); // => "I'm a humanoid carbon unit"
The downsides of this approach is that someone can freely instantiate an App.Person object. Moreover, you can't subclass multiple parent classes.
Anyway, I hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With