简体   繁体   中英

Handlebars not reading backbone.js model attributes

i am having some strange difficulties showing model attributes with handlebars and backbone.js here is the code.

 MYAPP.Menu = {}; MYAPP.Menu.Item = Backbone.Model.extend({ urlRoot : 'menuItem', defaults: { title: "Menu Item Title default", price: "menu item price default" }, }); 
MYAPP.Menu.Items = Backbone.Collection.extend({
    model: MYAPP.Menu.Item,
    url: 'menuItems'
});

MYAPP.Menu.ItemView = Backbone.View.extend({

    initialize : function() {
        this.model = new MYAPP.Menu.Item();
        this.model.on('all', this.render, this);
    },
    render : function() {
        var source = $("#index-template").html();
        var template = Handlebars.compile(source);
        console.debug(this.model.get("title")); <- shows default value
        var html = template(this.model);
        console.debug(html);
        this.$el.html(html);
        return this;
    }
});

And the template:

  <script type="text/x-mustache-template" id="index-template"> <div class="entry"> <h1>{{title}}</h1> <div class="body"> {{price}} </div> </div> </script> 

the output is nothing just the tags with out any data. no errors in console as well. Any ideas?

Well i have a solution:

When i am using

  initialize : function() { this.title = "Menu Item Title default"; this.price = "menu item price default"; }, 

Everything works fine. does anyone have an explanation for this

var html = template(this.model);

should be

var html = template(this.model.toJSON());

Basically, this.model has an attributes property that stores all of the information that you can retrieve using this.model.get() and set using this.model.set() . These properties aren't attached to the base model.

When you have the following code

initialize : function() {
    this.title = "Menu Item Title default";  // BAD!
    this.price =  "menu item price default"; // BAD!
}

You are attaching the attributes to the base model. This is incorrect use of Backbone. If you tried doing this.model.get("title") afterwards, it would be undefined .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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