Skip to content

Instantly share code, notes, and snippets.

@SachaG
Last active August 29, 2015 14:03
Show Gist options
  • Save SachaG/d57fccc728dd2959f8d0 to your computer and use it in GitHub Desktop.
Save SachaG/d57fccc728dd2959f8d0 to your computer and use it in GitHub Desktop.
Iron Router subscription loading pattern
// Global data controller
DataController = RouteController.extend({
onBeforeAction: function(pause) {
var loading = false, notFound = false;
_.each(this.routeData(), function (dataItem) {
var handle = dataItem.subscription;
if (dataItem.wait && ! dataItem.cursor.count()) {
if (handle.ready()) {
notFound = true;
} else {
loading = true;
}
}
});
// Case 1: not found
if (notFound) {
this.render('notFound');
return pause();
}
// Case 2: still loading
if (loading) {
this.render('loading');
return pause(); // (or use else if)
}
// Case 3: proceed to route
},
data: function() {
var data = {};
_.each(this.routeData(), function (dataItem) {
data[dataItem.name] = dataItem.cursor;
});
return data;
}
});
PostPageController = DataController.extend({
routeData: function() {
return [
{
name: 'post',
subscription: Meteor.subscribe('singlePost', this.params._id),
cursor: Posts.findOne(this.params._id),
persist: true, // Subscription Manager style subscription persistence?
wait: true
},
{
name: 'postComments',
subscription: Meteor.subscribe('postComments', this.params._id),
cursor: Comments.find({postId: this.params._id, parentCommentId: null}, {sort: {score: -1, postedAt: -1}}),
wait: false
},
{
name: 'postUsers',
subscription: Meteor.subscribe('postUsers', this.params._id),
wait: false
}
]
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment