【问题标题】:backbone.js: the template can't recognize the modelBackbone.js:模板无法识别模型
【发布时间】:2012-05-30 04:51:26
【问题描述】:

我有一个模板:

<script type="text/template" id="action-template-item">
    <span data-layer="<%= target%>" data-uuid="<%= uuid%>">delete</span>
</script>

我在视图中渲染模板

    window.ActionView = Backbone.View.extend({
          template: $("#action-template-item").html(),
          initialize: function () {
                this.render();
          },
          render: function () {
              var tmpl = _.template(this.template);
              console.log(this.model);//model have "target"
              this.$el.html(tmpl(this.model));
              return this;
          }

    });

模板只有两个来自模型数据的属性,

在渲染之前,我使用控制台检查模型是否有target值,答案是肯定的,就像上面的评论一样,

我的模型数据是这样的:

{
   target: "xxx-xxx-xxx",
   uuid: "xxx-xxx-xx"
}

但是萤火虫告诉我"target is not defined"

发生了什么?我的代码有什么问题?

【问题讨论】:

    标签: templates view model backbone.js underscore.js


    【解决方案1】:

    您的模型可能看起来像这样:

    var M = Backbone.Model.extend({});
    var m = new M({
       target: "xxx-xxx-xxx",
       uuid: "xxx-xxx-xx"
    });
    

    演示(打开控制台,你会看到你的错误):http://jsfiddle.net/ambiguous/Rnd6k/

    所以当你说

    //model have "target"
    

    您的意思可能是this.model.attributes.target 存在。 Backbone 模型属性和 JavaScript 对象属性不是一回事,Underscore 模板会寻找对象属性,它们对 Backbone 模型属性一无所知。

    通常的方法是在您想要渲染视图时使用toJSON 序列化您的模型:

    render: function () {
        var tmpl = _.template(this.template);
        this.$el.html(tmpl(this.model.toJSON()));
        return this;
    }
    

    演示:http://jsfiddle.net/ambiguous/Rnd6k/

    【讨论】:

    • 事实上,传入的this.model已经是模型的attributes属性之一,它没有toJSON方法,而且我认为this.model.attributes是aleady对象类型。你的意思是我需要把object类型转成json类型吗?
    • 现在我使用了一个 jquery json pulgin,使用 $.toJSON 方法将对象转换为 json 数据类型,但它仍然无法工作,告诉我target is not defined
    • 我知道我的代码出了什么问题。它是一个数组项!节点是一个对象类型!不过非常感谢
    猜你喜欢
    • 1970-01-01
    • 2012-11-21
    • 2012-09-08
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多