Lawrence
Lawrence

Reputation: 358

How to update a Handlebars template variable only on client-side using Meteor?

I want to learn how to update a single item in the template, just on client-side. If possible, provide an example of Session and MongoDB.

My simplest template file:

<template name="teste">
  <input type="button" value="Set one item" class="setitem" /><br><br>
  {{item1}}
</template>

And in my JS file I have:

if (Meteor.isClient) {

  Template.teste.events({

    'click .setitem' : function () {

      // What I put here to update the {{item1}}:

      // 1. Not Reactive (only on client)
      // 2. Reactive with Session
      // 3. Reactive with MongoDB

    }

  });  

}

Thanks.

Upvotes: 1

Views: 1593

Answers (1)

Joseph
Joseph

Reputation: 119837

Reactive

Think of reactive sources as "values coming from functions that are re-run to generate the values every update". In this example, we use a reactive source (a session value) to supply a value to item1. Changing the value triggers a re-calculation of item1 thus instantly producing the new value to the template.

// Supplying item1 from a reactive source (Session)
Template.teste.item1 = function(){
  Session.get('item1');
}

// Place this in the click handler
Session.set('item1','some_value');

Non-reactive

For values that don't use reactive sources, these functions are not re-run automatically. In the following example, we use a plain variable _item1 to supply the data. To reflect the changes of _item1 to item1, we create a Dependency object where we can bind the function to, so that when that Dependency object's change is triggered, it reruns all bound functions.

// A variable storing our real value. A non-reactive source.
Template.teste._item1 = '';
//Dependency object
Template.teste._item1Deps = new Deps.Dependency;

Template.teste.item1 = function(){
  // Bind the enclosing function to the Dependency object
  Template.teste._item1Deps.depend(); 
  return Template.teste._item1;
}

//In your handler
Template.teste._item1 = 'some_value'; //Change value does not trigger reactivity
Template.teste._item1Deps.changed();  //Rerunning all functions bound to the object

Upvotes: 3

Related Questions