I am working on a phonegap app using backbone.js. I have the following models:
- A Measure
- A Measures Collection (basis of the main view)
- A Code
- A Codes collection (child of Measure)
I then have the following Views
- Main Page
- List of Measures
- Measure page
- Code List Page (codedOptionsPage) (includes a header and then a div that is the container for the list)
- Code List collection view (codedItemListView, manages the list in the above page)
- Code Item (codedItemView - one for each list item)
I want the Measure object to be the model for all Views 3 - 6 so that, when anything changes, I can update the main object and save it.
What is happening in the code below is that, upon first render for the codedOptionsPage, the "this.model" is an instance of the Measure model. However, on subsequent calls to render triggered by adding a code to the Measure's code collection, "this.model" is a reference to the prototype, not an instance, so I get an error saying "Object function (){ return parent.apply(this, arguments); } has no method 'toJSON'"
I am pretty sure the code below is not what it should be, as I'm still struggling through this approach, and I'm happy to take general advice, but I'm particularly wondering what is happening to the model.
directory.views.codedOptionsPage = Backbone.View.extend({
events : {
"click a.add-item" :"add"
},
initialize: function () {
this.template = _.template(directory.utils.templateLoader.get('coded-options-page'));
this.model.attributes.codes.bind('add', this.render);
_.bindAll(this, "add");
},
add: function() {
var code = new directory.models.code();
this.model.attributes.codes.add(code);
},
render: function(eventName) {
$(this.el).html(this.template(this.model.toJSON()));
this.listView = new directory.views.codedItemListView({el: $('ul.codes', this.el), model: this.model});
this.listView.render();
return this;
}
});
directory.views.codedItemListView = Backbone.View.extend({
el: 'ul.code-list',
initialize: function() {
this.model.bind("reset", this.render, this);
},
render: function(eventName) {
$(this.el).empty();
_.each(this.model.attributes.codes, function(code) {
var li = new directory.views.codedItemView({model: code}).render().el;
$("#code-list").append(li);
}, this);
return this;
}
});
directory.views.codedItemView = Backbone.View.extend({
tagName: "li",
initialize: function() {
this.template = _.template(directory.utils.templateLoader.get('coded-item'));
},
render: function(eventName) {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
Thanks for looking!