Skip to content

Instantly share code, notes, and snippets.

@alexdiliberto
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexdiliberto/9379909 to your computer and use it in GitHub Desktop.
Save alexdiliberto/9379909 to your computer and use it in GitHub Desktop.
Ember Longpolling
/**
Ember Longpolling
Periodically poll to update posts with latest comments
*/
//Create Pollster Object
App.Pollster = Ember.Object.extend({
start: function() {
this.timer = setInterval(this.onPoll.bind(this), POLL_INTERVAL);
},
stop: function() {
clearInterval(this.timer);
},
onPoll: function() {
// Issue JSON request and add data to the store
}
});
//Setup Pollster in the Route
App.PostRoute = Ember.Route.extend({
setupController: function(controller, model) {
var route = this;
if(Ember.isNone(this.get('pollster'))) {
this.set('pollster', App.Pollster.create({
onPoll: function() {
Ember.$.getJSON('/updates', 'GET').then(function(json_obj) {
// The JSON structure is as follows:
//{
// comments: [
// { ... }
// ]
//}
}
// Iterate through the comments
json_obj.forEach(function(comment) {
// Make sure that the comment is not already in the store
if(!route.get('store').recordIsLoaded(App.Comment, comment.id)) {
route.get('store').push('comment', comment);
}
})
}
}));
}
this.get('pollster').start();
},
deactivate: function() {
this.get('pollster').stop();
}
});
/* post.hbs */
<article class="post">
<h2>{{title}}</h2>
<p>{{content}}</p>
<aside>{{render "comments" comments}}</aside>
</article>
App.PostController = Ember.ObjectController.extend({
comments: function() {
var postId = this.get('id');
// Get all the comments that belong to this post
return this.get('store').filter('comment', function(comment) {
return comment.get('post.id') === postId;
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment