Can I add (static) class methods using EmberJS mixins

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() 

Is it possible to create a mixin that will add class methods?

+7
source share
2 answers

Yes, you can!

Just enter mixin while calling reopenClass:

 // 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 also came across this problem and found that this is being done in the Discourse project.

Hope this helps!

+13
source

First of all, I'm still learning EmberJS. :)

I had the same problem: how to add generic classes to a class.

I understand that you cannot do this with Mixins ( Warning : I may be wrong), but you can do this using a simple subclass.

Take a look at jsbin . App.Soldier is a subclass of App.Person that contains instance and class methods. They are available for 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 disadvantages of this approach are that someone is free to instantiate an App.Person object. In addition, you cannot subclass multiple parent classes.

Anyway, I hope this helps

+1
source

All Articles