Last active
January 2, 2016 18:30
-
-
Save gfargo/9d5f19a3fea0d0e8c667 to your computer and use it in GitHub Desktop.
Using ReactiveVars in Meteor Templates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Basic Items Template | |
// Great read on Reactivity in Meteor - https://www.discovermeteor.com/blog/reactivity-basics-meteors-magic-demystified/ | |
// Called when Items template is first created - but not yet added to the DOM | |
Template.Items.onCreated(function() { | |
// Store template instance into expanitory variable | |
var template = this; | |
// Initialize the reactive variables by attaching them to the current template instance | |
template.loaded = new ReactiveVar(0); | |
template.limit = new ReactiveVar(5); | |
// Autorun function set on the Template instance | |
// This function will rerun when one of the 'computations' within changes. | |
// Tracker Docs - https://github.com/meteor/meteor/wiki/Tracker-Manual | |
template.autorun(function () { | |
// get the limit | |
var limit = template.limit.get(); | |
// subscribe to the posts publication | |
var subscription = template.subscribe('items', limit); | |
// if subscription is ready, set limit to newLimit | |
if (subscription.ready()) { | |
// Subscription is now ready to be | |
template.loaded.set(limit); | |
} else { | |
console.log("Subscription Not Ready"); | |
} | |
}); | |
// Store subscription into variable attacted to template | |
template.items = function() { | |
console.log('querying items'); | |
return Items.find({feed: template.data.handle}, {limit: template.loaded.get()});; | |
} | |
}); | |
// Template Events | |
Template.Items.events({ | |
'click .load-more': function(event, template) { | |
event.preventDefault(); | |
console.log('Load More Clicked', template); | |
// get current value for limit, i.e. how many posts are currently displayed | |
var limit = template.limit.get(); | |
// increase limit by 5 and update it | |
limit += 5; | |
template.limit.set(limit); | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment