I have the following HTML code:
<ul id='item-list'></ul>
<button id='add-item'>Add Item</button>
<script type='text/template' id='item-template'>
<li><%= title %></li>
</script>
and the following javascript / backbone js code:
var Item = Backbone.Model.extend({});
var ItemCollection = Backbone.Collection.extend({
model: Item
});
var ItemListView = Backbone.View.extend({
el : $("#item-list"),
initialize(options) {
this.item_collection = new ItemCollection();
},
appendItem: function() {
new_item = new Item({'title' : 'New Item'});
this.item_collection.add(new_item);
item_template = $("#item-template");
item_html = _.template(item_template,new_item.toJSON());
this.el.append(item_html);
}
});
var AddItemView = Backbone.View.extend({
el: $("add-item"),
events: {
"click" : "addItem"
},
addItem: function() {
// ?
}
});
item_list_view = new ListItemView();
add_item_view = new AddItemView();
How can I add a new item to the item list view and collection from an event in the addItemView View? also, should the creation of the model, appending it to the collection, and appending it to the view all take place in the ListItemView.addItem() function, or should I instead have it binded to the add event of the ItemCollection ? I am still having some trouble wrapping my head around the way bindings and the interactions between various views, models, and collections should work.
here’s an example of events between 2 views working with a model/collection. Basically, use collectionName.bind(‘add’,yourFunction,this);