I have an API which can't suitable for Ember-Data's Rest Adapter. There about 3 models, thus I decided to use plain old $.ajax from jQuery. I blown my mind while finding a way how to retrieve models and pass them to controller in a right way.
Consider the following example from guides:
App.Router.map(function(match) {
match('/posts').to('posts');
});
App.PostsRoute = Ember.Route.extend({
model: function() {
return App.Post.findAll(); // Just renamed to .findAll.
}
});
I found that .findAll method must return an instance of E.ArrayProxy, otherwise it's impossible to do things like this:
{{#if content}}
...
{{else}}
<strong>Nothing to display</strong>
{{/if}}
And my implementation look so:
App.Post.reopenClass({
findAll: function() {
var result = Ember.ArrayProxy.create({content: []});
$.getJSON('/posts', function(data) {
$.each(data, function(i, row) {
result.pushObject(App.Post.create(row));
});
});
return result;
}
});
I am pretty satisfied with this, but I can't imagine how to work with single object.
App.PostsRoute = Ember.Route.extend({
model: function(params) {
return App.Post.find(params.post_id);
}
});
// This will not work for me. Controller's content property will alway be null.
App.Post.reopenClass({
find: function(postId) {
var result = null;
$.getJSON('/' + postId, function(data) {
result = App.Post.create(data);
});
return result;
}
});
What is the solution?
Should I return dummy Ember.ObjectProxy instance with empty content and somehow let Ember know after content actually populated with object? What is a golden path?
You can use just a plain, old object which is basically how ember-data does it.
App.Post.reopenClass({
find: function(postId) {
// Set some default properties here.
var result = Ember.Object.create({
isLoaded: false
});
$.getJSON('/' + postId, function(data) {
result.setProperties(data);
result.set('isLoaded', true);
});
return result;
}
});
Is this the golden path? Probably not, the more you dive into Ember the more you will want the rich set of features promised by ember-data. A few months back I wrote my own framework. Terrible compared to ember-data, but it didn't require root elements, side loaded data, underscored names, and supported embedded relationships. I am hopeful that ember-data will be addressing these as it matures and I know they have been hard at work making it easier to swap out adapters and serializers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With