I am newbie in client side Javascript MVC, first ember.js app.
I follow the instructions here to use ember-rest in creating a post-comments type of nested models.
http://www.cerebris.com/blog/2012/01/26/beginning-ember-js-on-rails-part-2/
I started writing nested resources as follow:
resources :conversations do
resources :comments
end
Now the problem is when I had to write the ember-rest controller:
App.commentsController = Ember.ResourceController.create({ resourceType: App.Comment resourceURL: '/conversations/:id/comments' });
I don't think I can use the :id in the middle; how could I work around that? Does ember-data solves this? It seems spine.js integration will be slightly easier to handle this. Thanks in advance!
I've been meaning to answer your comment on my post from yesterday, so I'm glad you asked the question here.
I should start by saying that I wrote ember-rest as a very thin layer over jQuery.ajax. It's not terribly advanced, and there is not even a built-in facility for associations. However, I am considering adding one now that this lib is getting a fair bit of use. As you'll see from the code below, this concept can be handled but should be better abstracted in the lib.
Associations can be handled by creating an instance of a resource controller within each parent resource. Each particular resource controller should manage a particular array of resources, but not necessarily all the resources of a particular type.
In your case, you could extend ResourceController to manage comments for conversations:
App.ConversationComments = Ember.ResourceController.extend({
resourceType: App.Comment,
// override _resourceUrl() to base the url on the conversation
_resourceUrl: function() {
return this.get("conversation")._resourceUrl() + "/comments";
}
});
You could then configure an instance of ConversationComments for each conversation:
App.Conversation = Ember.Resource.extend({
resourceUrl: '/conversations',
resourceName: 'conversation',
resourceProperties: ['prop1', 'prop2']
// init comments
init: function() {
this.set("comments", App.ConversationComments.create({ conversation: this }));
}
});
Last but not least, you'll need to retrieve the comments for each conversation:
conversation.get("comments").findAll();
If you have all the comments in json, you could alternatively use loadAll(). Where and when you call loadAll() or findAll() depends on your app's needs. Obviously, you will want to reduce the number of ajax calls for best performance.
Ember-data is a much more ambitious project than ember-rest, and already has support for associations as well as advanced features such as transactions. With that said, it's under very active development with a changing API. If you're patient and willing to dig into the code, I highly recommend trying it out. When the dust settles a bit, I also plan to blog about it.
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