Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Can I create a mixin that adds class methods?

like image 810
Amir T Avatar asked May 20 '13 23:05

Amir T


2 Answers

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!

like image 191
Dan G. Avatar answered Nov 10 '22 23:11

Dan G.


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

like image 27
David Avatar answered Nov 10 '22 22:11

David