Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why/when do you need to reopen classes in ember.js?

Tags:

ember.js

There are times when you use App.Model.reopenClass() on a model (link) and the Ember guides talk about App.Router.reopen() (link). From the Ember guides:

reopen is used to add instance methods and properties that are shared across all instances of a class. It does not add methods and properties to a particular instance of a class as in vanilla JavaScript (without using prototype).

But when you need to create class methods or add properties to the class itself you can use reopenClass.

When is this necessary/advantageous? Is it not possible to just add everything right up front?

like image 204
doub1ejack Avatar asked Nov 14 '13 21:11

doub1ejack


2 Answers

reopenClass is analogous to adding methods to the prototype instead of adding methods on each and every instance of your classes. You can think of them as static variables/methods, instead of instance variables/methods.

It's a major performance gain, and possibly makes more sense for the problem you are solving.

like image 124
Kingpin2k Avatar answered Oct 16 '22 20:10

Kingpin2k


One example where you would reopen a class is that when you want to add properties to an existing default generated class. For example: many instances of ember applications don't extend router class. They just use default router class. But what if you want to add some properties to router class that you want to use somewhere else. reopen is pretty usefull there. This is one use case I can think of.

Also, In the case of Router extending the class is difficult as most of the code within ember just uses router class. Even if you extend, some callbacks/closures will still refer to the older router class.

like image 26
VNarasimhaM Avatar answered Oct 16 '22 18:10

VNarasimhaM