繁体   English   中英

传递模型对象到骨干中查看

[英]passing model object to view in backbone

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

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:我正在使用下划线模板引擎

此外,将模型传递给视图的方式也不灵活,因为您将传递模型的实例,而不是默认模型。 因此,你可能想要挑出来

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/

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM