2013-10-26 44 views
9

我一直试图传递一个模型对象以在我的模板中进行评估,但没有运气。我尝试以下,但没有运气传递模型对象以在骨干中查看

dashboardmodel.js

var myMod = Backbone.Model.extend({ 
    defaults: { 
    name: "mo", 
    age: "10" 
    } 
}); 

myview.js

  var dashView = Backbone.View.extend({ 

     el: '.content-area', 

     this.mymodel = new myMod({}), 

     template: _.template(dashBoardTemplate, this.mymodel), 
     initialize: function() { 
        }, 

        render: function() { 
         this.$el.html(this.template); 
         return this; 
        } 

// more javascript code............. 

dahboard.html

<p> Hello <%= name %> </p> 

PS:我使用下划线模板发动机

+0

只需编辑您的模板使其可渲染,并在渲染函数中传递model.toJSON()或model.attributes,但不要传递模型本身。 [BACKBONE DOCS](http://backbonejs.org/#View-template) –

回答

3

你需要得到一个Bacbone模型propertis与吸气语法,所以你需要你的模板重写:

<p> Hello <%= obj.get('name') %> </p> 

,或者您需要调用_.template你可以做什么时,你的模型转换成一个普通的JS对象与.toJSON()(用来创建模型的克隆)或.attributes属性:

template: _.template(dashBoardTemplate, this.mymodel.toJSON()) 

旁注:你应该考虑到模板呈现逻辑进入你的看法。因为你当前的代码使您的模板时,您的看法声明,而不是当你调用render方法。所以你可能会得到意想不到的结果。所以,你的代码是这样的:

template: _.template(dashBoardTemplate), //only compile the template 
render: function() { 
    this.$el.html(this.template(this.mymodel.toJSON())); 
    return this; 
} 
+0

这太棒了!感谢第二种方法的魅力 – tawheed

5

此外,用自己的方式传递模型视图不灵活,因为你会通过,而不是默认的模式模型的实例。因此,你可能想挑出

this.mymodel = new myMod({}), 

(顺便说一句,上面的线给我的错误消息,因为“=”号我的Chrome浏览器)

然后,假设你有一个实例:

A = new myMod({"name": "World", "age":100}) 

然后将它传递到您的视图为:

myview = new dashView({mymodel: A}) 

一个步骤,你所要做的就是调用渲染功能:

myview.render(); 

下面是一个完整的解决方案:

<html> 
<script src="jquery-1.10.2.min.js"></script> 
<script src="underscore-min.js"></script> 
<script src="backbone.js"></script> 
<body> 
<script type="text/template" id="dashBoardTemplate"> 
<p> Hello <%= name %> </p> 
</script> 
<div class="content-area"> 
</div> 
<script type="text/javascript"> 
var myMod = Backbone.Model.extend({ 
    defaults: { 
    name: "mo", 
    age: "10" 
    } 
}); 

var dashView = Backbone.View.extend({ 
    el: '.content-area', 
    template: _.template($("#dashBoardTemplate").html()), 
    render: function() { 
     this.$el.html(this.template(this.model.toJSON())); 
     return this; 
    } 
}); 
mymod = new myMod({"name": "World", "age":100}); 
myview = new dashView({model:mymod}); 
myview.render(); 
</script> 
</body> 
</html> 

如果你想学习backone.js,请仔细阅读本开源的书,让我开始:

http://addyosmani.github.io/backbone-fundamentals/