Backbone.js的不拾取模式的上下文 [英] backbone.js not picking up model context

查看:149
本文介绍了Backbone.js的不拾取模式的上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参见下面的小提琴

HTML

<script id="person" type="text/x-handlebars-template">        
    <div>Title : {{title}} </div>  
    <div>First Name : {{firstname}}</div>
    <div>Last Name : {{lastname}}</div>                      
</script>
<div id="people"></div>

JS

(function ($) {
       var personTemplate= Handlebars.compile($("#person").html());

       var Person= Backbone.Model.extend({
           title: null,
           firstname : "",
           lastname : ""
        });

        PersonView = Backbone.View.extend({
            tagName: "div",
            template:  personTemplate,
            render: function () {
                $(this.el).html(this.template(this.model));
                return this;
            }
        });

        $(document).ready(function () {
        var AppView = Backbone.View.extend({
            initialize: function () {              
                var passView = new PersonView (
                    { model: new Person({ title: "Mr",
                                          firstname : "John",
                                          lastname : "Smith"})
                    });

                $('#people').append(passView.render().el.outerHTML);
            }
        });

        var App = new AppView();
    });
})(jQuery);

我创建了一个基本的模式和视图,但该视图的参数没有被模板回升。如果我的价值直接对人的模型设定,找到他们。但如果我通过模式的新实例设置它们(或者即使我使用init方法来.SET()他们。

I've created a basic mode and view, but the parameters for the view are not being picked up by the template. If i set the value directly on the person model, it finds them. But not if i set them via a new instance of the mode (or even if I use the init methods to .set() them.

我在做什么错了?

推荐答案

为了得到一个对象与模板的使用,你需要打电话给你的模型的的toJSON 方法。

In order to get a object for use with your template you need to call your model's toJSON method.

例如

PersonView = Backbone.View.extend({
            tagName: "div",
            template:  personTemplate,
            render: function () {
                $(this.el).html(this.template(this.model.toJSON()));
                return this;
            }
        });

如果您检查在Firebug(或只是将其输出到控制台)的车型​​之一,你会发现有很多更多的属性,那么你指定的只是那些和您指定的值,实际上是下载物业的属性的,叫的toJSON 返回模型对象的价值观的所指定。

If you inspect one of your models in Firebug (or just output it to the console) you'll notice that there are a lot more attributes then just the ones you specified, and that the values you specify are actually contained under a property attributes, calling toJSON returns an object with the models "values" that you specified.

这篇关于Backbone.js的不拾取模式的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆