2012-05-30 32 views
0

我有一个模板:Backbone.js的:模板不能识别模型

<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"

发生了什么事有什么错我的代码?

回答

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/

+0

事实上,'this.model'传入已经是一个该模型的属性属性,它没有'toJSON'方法,我也认为'this.model.attributes'是对象类型。你的意思是我需要将对象类型转换为json类型? – hh54188

+0

现在我已经使用jQuery json pulgin,使用$ .toJSON方法将对象转换为json数据类型,但它仍然无法正常工作,请告诉我'未定义目标' – hh54188

+0

我已经知道我的代码有哪些错误。它是一个数组项!节点是一个对象类型!不过非常感谢 – hh54188