UI Reactivity in Slow Motion

In this episode we'll take a step back from the details of Spark, and look in slow motion at the user interface updating because of a reactive data source

Start Watching Loading...

That's it for "UI Reactivity in Slow Motion". Good job!

Next

Need a second look? Watch again.

UI Reactivity in Slow Motion

In this episode we'll take a step back from the details of Spark, and look in slow motion at the user interface updating because of a reactive data source. In this screencast we'll use a list for our example. We'll have a parent template that uses the `{{#each items}}` helper to iterate over a list of items and render a `listItem` template for each list item.

First we'll look at what happens when the items helper just returns a simple array. Next, we'll look at what happens when we return an array by calling the `find().fetch()` methods on a Collection. Finally, we'll see what happens when we just return a cursor by calling the `find()` method on the Collection.<br> In each example, we'll see the UI reactively updating in slow motion by setting some breakpoints in the Meteor source code. <p class="code-block-title">reactive-ui.js</p> ```javascript if (Meteor.isClient) { // Create a client side only collection that doesn't sync with the server DocumentCollection = new Meteor.Collection(null); // A regular non-reactive array var items = [{ _id: 1, title: "One" }, { _id: 2, title: "Two" }]; // seed our collection with 3 documents function seed () { for (var i = 0; i < 3; i++) { DocumentCollection.insert({ title: "Document " + i }); } } Meteor.startup(seed); Template.list.helpers({ items: function () { // Returns a Cursor. This works hand in hand with the // {{#each items}} helper to only update the individual // list dom items that have changed vs. updating the entire // parent template and all its children. return DocumentCollection.find(); }, onlyParentTemplateReactivelyUpdates: function () { // Calling find() sets up a reactive context. So if any data in // the cursor changes, this context will be invalidated and the // list template will be re-rendered. The key takeaway is that // all children templates will be re-rendered as well. var array = DocumentCollection.find().fetch(); return array; } notReactiveItems: function () { // This just returns an array. An array is not a "reactive data source" // so it doesn't invalidate contexts when data has changed and the // template won't re-render if the array's data changes. return items; } }); // Let's see in the console when each template renders Template.list.rendered = function () { console.log("rendered list"); }; Template.listItem.rendered = function () { console.log("rendered listItem"); }; } ```