This is my first attempt to use Backbone.js, so I decided to create a simple test application that simulates a restaurant menu with menu elements. I followed this cool blog post from andyet.net .
I had a problem adding a model to the collection. I associated the view method with a collection add event, which should update the view. Here is the code with the maximum code removal possible.
(note: for brevity, I deleted things like local declarations varand closures. Below is still a bit, and I know this is annoying, but it should be pretty simple and easy to understand):
MenuItem = Backbone.Model.extend({
});
Menu = Backbone.Model.extend({
});
MenuSelection = Backbone.Collection.extend({ model: MenuItem });
MenuItemView = Backbone.View.extend({
});
RestaurantAppView = Backbone.View.extend({
addMenuItem : function (MenuItem) {
var view = new MenuItemView({ model : MenuItem });
this.menuList.append(view.render().el);
},
initialize : function () {
this.model.MenuSelection.bind('add', this.addMenuItem);
},
render : function () {
$(this.el).html(ich.app(this.model.toJSON()));
this.menuList = this.$('#menuList');
return this;
}
});
RestaurantAppController = {
init : function (spec) {
this.config = { connect : true };
_.extend(this.config, spec);
this.model = new Menu({
name : this.config.name,
});
this.view = new RestaurantAppView({ model : this.model });
return this;
}
};
$(function() {
var json = {
Menu : {
name : 'Appetizers',
MenuItem : [
{
name : 'toast',
description : 'very taosty',
price : '$20.00'
},
{
name : 'jam',
description : 'very jammy',
price : '$10.00'
},
{
name : 'butter',
description : 'very buttery',
price : '$26.00'
}
]
}
};
window.app = RestaurantAppController.init({
name : json.Menu.name
});
$('body').append(app.view.render().el);
app.model.MenuSelection.add(json.Menu.MenuItem);
});
. :
jQuery Zepto , $, , .
, this.menuList = this.$('#menuList'); , this.menuList addMenuItem? , , . , this.menuList jQuery, :
addMenuItem : function (MenuItem) {
var view = new MenuItemView({ model : MenuItem });
$('#menuList').append(view.render().el);
}
. menulist , addMenuItem. RightWay TM - .
: , , ICanHaz , this.menuList , undefined, .