backbone.js not picking up model context

一世执手 提交于 2020-01-24 13:14:05

问题


Please see the following fiddle.

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

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.

What am I doing wrong?


回答1:


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

For example

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

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.



来源:https://stackoverflow.com/questions/13496231/backbone-js-not-picking-up-model-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!