传递模型对象视图在主链

问题描述 投票:9回答:2

我一直在试图通过在我的模板进行评估的模型对象,但没有运气。我尝试以下,但没有运气

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

dashboard.html

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

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

javascript backbone.js
2个回答
3
投票

你需要得到与吸气语法主干网模型性质,所以你需要重写你的模板:

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

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

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;
}

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/

© www.soinside.com 2019 - 2024. All rights reserved.