Json数据没有使用每个附加在Meteor模板中

时间:2014-07-03 22:31:13

标签: javascript json templates meteor append

我试图让我的json数据附加到模板中。我的模板中会有几个对象,我使用{{#each products}}。 Json数据似乎出现在控制台中,但模板中的数据没有任何反应。

这是我的js:

 if (Meteor.isClient) {
  Template.product_items.products = function () {
    Meteor.call('getProducts', function(error, result){
      var products = JSON.parse(result.content).products;
      console.log(products);
    }) 
  }
}


if (Meteor.isServer) {
  Meteor.startup(function () {
    Meteor.methods({
      getProducts: function(){
        return HTTP.call("GET", "https://api.url.com/products",
          {params: {access_token: "***"}});
      }
    });
  })} 

我的观点:

<body>
  {{> product_items}}
</body>

  <template name="product_items">
   {{#each products}}
   <div class="col-md-3">
    <img src="{{preview_url}}"  class="img-thumbnail">
    <h4>{{name}}</h4>
    <p>{{description}}</p>
    <p>
      <a href="{{short_url}}">More</a>
    </p>
  </div>
  {{/each }}

</template>

console.log(products);为我提供了正确的数据:

[Object, Object]
  0: Object
    description: "<p>it's what you need</p>"
    name: "wow product"
    preview_url: "erl.jpg"
    webhook: null
    __proto__: Object
  1: Object
    description: "<p>okok</p>"
    name: "wow nemr"
    preview_url: "surl.jpg"
    webhook: null
    __proto__: Object
  length: 2
  __proto__: Array[0]

但它没有出现在模板中。我做错了什么?

1 个答案:

答案 0 :(得分:2)

您需要Template.product_items.products函数返回您的值。当然,当您使用方法时,这不可能直接实现,因为方法在客户端上是异步的。你需要利用助手的反应能力。

示例:

var products = null;
var productsDep = new Tracker.Dependency();

Template.product_items.rendered = function() {
  products = null;
  Meteor.call('getProducts', function(error, result) {
    products = JSON.parse(result.content).products;
    productsDep.changed();
  });
};

Template.product_items.helpers({
  products: function() {
    produtsDep.depend();
    return products;
  },
});