【问题标题】:Handlebars Template not able to process JSON from BackboneHandlebars 模板无法处理来自 Backbone 的 JSON
【发布时间】:2011-08-16 20:29:08
【问题描述】:

Handlebars 无法读取我将其作为上下文发送的 JSON 对象。

这是调用 Mustache 模板并为其提供上下文的函数:

render: function() {
  var source = $("#round").html();
  var template = Handlebars.compile(source);
  var context = JSON.stringify(this.model);
  console.log(context);
  var html = template(context);
  $(this.el).html(html);
  return this;
},

这是我传递给它的 JSON 对象:

{"result":0,"friend1":{"firstName":"Ape","lastName":"Head","fbID":329018,"kScore":99,"profilePic":""},"friend2":{"firstName":"Ape","lastName":"Hands","fbID":32,"kScore":70,"profilePic":""}}

这是 Handlebars 模板:

  <script id="round" type="text/x-handlebars-template">
    {{#with friend1}}
    <h2>{{firstName}} {{lastName}}</h2>
    {{/with}}
  </script>

我收到以下错误:

Uncaught TypeError: Cannot read property 'firstName' of undefined

【问题讨论】:

    标签: javascript json backbone.js handlebars.js


    【解决方案1】:

    替换这个函数:

    render: function() {
      var source = $("#round").html();
      var template = Handlebars.compile(source);
      var context = JSON.stringify(this.model);
      console.log(context);
      var html = template(context);
      $(this.el).html(html);
      return this;
    },
    

    与:

    render: function() {
      var source = $("#round").html();
      var template = Handlebars.compile(source);
      var context = JSON.parse(this.model.toJSON);
      console.log(context);
      var html = template(context);
      $(this.el).html(html);
      return this;
    },
    

    template 在这种情况下应该采用 javascript 对象。 JSON.stringify 返回 JSON 对象的字符串表示,而不是 javascript 对象。但你真正想要的是模型的属性。因此,您可以通过 toJSON 或 JSON.stringify(this.model) 访问它们,但是您需要将它们转换回 Javascript 对象。

    【讨论】:

    • 嗯,好像没用。 "this.model" 是一个 Backbone 对象,这就是我向模板传递 JSON 字符串的原因。
    • 这可能看起来很奇怪,但请尝试:JSON.parse(JSON.stringify(this.model))
    • 好的,我会在你编辑后检查你(不知道检查是否会阻止你编辑,所以我会等待。)
    【解决方案2】:

    只需在模板调用中使用.toJSON(),这会将模型属性转换为把手所需的json对象:

    template(this.model.toJSON());
    

    【讨论】:

      【解决方案3】:

      试试:

      var html = template(this.attributes);
      

      Backbone 模型对象的attributes 属性包含数据的JS 对象表示。像这样直接访问它并不是一个好习惯,但在这种情况下,它可能是最简单的事情,而不是尝试通过 JSON 来回传输数据。

      【讨论】:

        【解决方案4】:

        对于最快的方法,我必须同意 Dan 的回答。 对于您可能需要 id 来捕获点击的列表,您甚至可以这样做

        <script id="round" type="text/x-handlebars-template">
        {{#each friends}}
        <li id="{{ this.id }}" >{{this.attributes.firstName}} {{this.attributes.lastName}}</li>
        {{/each}}
        </script>
        

        【讨论】:

          猜你喜欢
          • 2014-03-11
          • 2012-09-08
          • 2014-06-05
          • 2014-06-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-10
          • 1970-01-01
          • 2012-04-10
          相关资源
          最近更新 更多