Reputation: 10077
I'm looking for a way to extend Ember's Object to include some additional methods, so that they become available every object (View, ArrayController, etc) in my app.
Specifically, I want to define some methods that introduces some naming conventions of the controllers, models, views, templates, helpers, etc.
For example:
If the class name of the View is ArticlesListView
then its associated model is Article
, the controller action is named list
within ArticlesController
, the template is in app/articles
named list.js.hjs
...
The end result should be, for example, App.ArticlesListView.model()
would return App.Article
.
So how do I extend the core Ember Object?
Ember.Object.extend({ // <--- ???
model: function(context, params){
}
});
Upvotes: 3
Views: 1677
Reputation: 6373
Basically like Luke wrote, with one substantial difference. If you do:
Ember.Object.reopen({
foo: function(){
return 'bar';
}
});
Above replace (not extend - if foo
method exist already) Object
's property foo
.
If you want to extend Ember Object
's property foo
you need to call _super()
in order to include original implementation of the foo
method.
Ember.Object.reopen({
foo: function(){
this._super(); // include original `foo` method stuff here
return 'bar'; // then add to `foo` method whatever you want
}
});
BTW, you can extend particular instance as well. var someObject = Ember.Object.extend({}); someObject.reopen({});
Upvotes: 1
Reputation: 8389
The answer to the general question of enhancing an existing object is to use reopen
:
Ember.Object.reopen({
foo: function(){
return 'bar';
}
});
As to your more specific question, that is more challenging. An object doesn't typically know about the name of the property it is assigned to. You might be able to achieve your goal by traversing the properties of your namespaces (including App
) and find the one that matches the current class. You could cache that property name for future performance.
Another approach would be to define a helper method for defining new models, controllers, etc. which you pass the name into. The method could handle creating the subclass, assigning it to a property of App, and setting an instance variable with the name.
Upvotes: 8