9

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

仪表板模型.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.............

仪表板.html

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

PS:我使用的是下划线模板引擎

4

2 回答 2

5

此外,将模型传递给视图的方式并不灵活,因为您将传递模型的实例,而不是默认模型。因此,您可能想单独列出

this.mymodel = new myMod({}),

(顺便说一句,由于“=”符号,上面的行在我的 chrome 浏览器中给了我错误消息)

然后,假设您有一个实例 A:

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/

于 2013-10-26T18:00:54.560 回答
3

您需要使用 getter 语法获取主干模型的属性,因此您需要将模板重写为:

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

_.template或者,您需要在调用.toJSON()(创建模型的克隆)或属性时将模型转换为普通的 JS 对象.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;
}
于 2013-10-26T17:41:11.673 回答