Today, I was playing with Ember Model while looking at refactoring from a raw Backbone project to Ember.
Since writing this article, I have found a more useful
reopen
method within Ember's Object Model.
One of the things that immdiately hit me was that all requests are built by appending .json
.
This could be ok, but it would take some re-routing across my entire api and there are 3rd party APIs that I need to interface with that do not end in .json
.
Luckily, this was super easy by using the Ember.RESTAdapter.extend
function.
I just needed to hack into a the buildURL
and remove the .json
endings.
In my asset pipline, I created a ember-model-updater.js
file and made sure it loaded after ember.js
and ember-model.js
.
In here I created the following:
Ember.RESTAdapter = (function(){
var get = Ember.get;
return Ember.RESTAdapter.extend({
buildURL: function(klass, id) {
var urlRoot = get(klass, 'url');
if (!urlRoot) { throw new Error('Ember.RESTAdapter requires a `url` property to be specified'); }
if (!Ember.isEmpty(id)) {
return urlRoot + "/" + id;
} else {
return urlRoot;
}
}
});
})();
It's pretty straight forward, but there was one little gimmick that I had to search through the Ember Model source to find the issue.
The problem was the get
function which after some digging was a reference to Ember.get
.
So, as I am becoming a bit more of a mature Javascripter, I wrapped it in an SIAF and returned it to Ember.RESTAdapter.
Now, the RESTAdapter works just like usual without appending .json
.
Since originally writing this article, I have found the reopen
function on Ember's Object Model, which takes out a bit of the confusion in the original code.
Reopen allow us to modify private functions and variables within any Ember Object. Since Ember Model extends Ember Object we can use this to our advantage and speed up our code a little bit.
(function(){
var get = Ember.get;
Ember.RESTAdapter.reopen({
buildURL: function(klass, id) {
var urlRoot = get(klass, 'url');
if (!urlRoot) { throw new Error('Ember.RESTAdapter requires a `url` property to be specified'); }
if (!Ember.isEmpty(id)) {
return urlRoot + "/" + id;
} else {
return urlRoot;
}
}
});
})();