I have a parent model that has many child models, for example:
App.Blog = Ember.Object.extend({})
App.Comment = Ember.Object.extend({})
Then I have a view for the Blog:
window.App.BlogView = Ember.View.extend
templateName: 'app_templates_blog'
Now, when I initially retrieve a Blog via my REST API, it contains the first 10 Comments or so. Those are instantiated like this:
window.App.Blog.reopenClass
create: (obj) ->
Object.tap @_super(obj), (result) =>
if result.comments
result.comments = result.comments.map (p) => App.Comment.create(p)
I display by blog by calling BlogView.set(‘blog’, blogInstance) and everything is displaying perfectly.
However!
I am implementing an infinite scroll, so when the end user gets to the bottom of the comments, I want to load more. I do this via REST, but I can’t for the life of me get them to display by appending them.
This is what my morePosts() method looks like in BlogView:
moreComments: () ->
blog = @get('blog')
jQuery.getJSON "/blogs/#{blog.get('id')}/comments", (result) =>
comments = blog.get('comments')
result.each (c) => comments.push(App.Comment.create(c))
blog.set('comments', comments)
this.set('blog', blog)
However, this never seems to add the new comments. What am I doing wrong here?
To properly support Ember’s bindings and observers, you need to use KVO aware getters and setters. Just as you use
getandsetfor standard properties, you also have to use special methods for Arrays. In this case, you’d usepushObject. You can see a full list of the functions implemented here: https://github.com/emberjs/ember.js/blob/master/packages/ember-runtime/lib/mixins/mutable_array.js.