What is the proper way to manipulate template instance in Meteor framework?

前端 未结 2 1936
Happy的楠姐
Happy的楠姐 2021-01-15 13:14

I am new to Meteor and wondering how to solve what seems to me is a common problem.

Let\'s say I have a handlebars template listing restaurants:

<         


        
2条回答
  •  梦谈多话
    2021-01-15 13:16

    You should use {{#if}} and Session. Like this:

    
    

    By using Session, a reactive data source, you can set a global flag indicating whether a restaurant is selected.

    Template.Restaurants.restaurantSelected = function() {
      // check whether this restaurant is selected. "this" refers to the current
      // context, eg. the current restaurant in the loop
      return Session.equals("restaurantSelected", this._id);
    }
    

    Whenever you change that session key, the value will update and the template will be redrawn. So, you can toggle it when clicking a restaurant:

    Template.Restaurants.events({
      'click' : function (e) {
        // store the current restaurant ID
        // make sure the event selector is correct!
        Session.set("restaurantSelected", this._id);
      }
    });
    

    Edit For clarity's sake I created a complete example that you can copy into your project and try out.

提交回复
热议问题