我从此处的 Backbone.js 教程中获得了这段代码。代码如下:
(function($){
var Item = Backbone.Model.extend({
defaults: {
part1: 'Hello',
part2: 'World'
}
});
var ItemList = Backbone.Collection.extend({
model: Item
});
var ItemView = Backbone.View.extend({
tagName: 'li',
initialize: function(){
_.bindAll(this, 'render');
},
render: function(){
$(this.el).html("<span>" + this.model.get('part1') + " " + this.model.get('part2') + "</span>");
return this;
}
});
var AppView = Backbone.View.extend({
el: $('body'),
initialize: function(){
_.bindAll(this, 'render', 'addItem', 'appendItem');
this.collection = new ItemList();
this.collection.bind('add', this.appendItem)
this.counter = 0;
this.render();
},
events: {
'click button#add': 'addItem'
},
addItem: function(){
var item = new Item();
item.set({
'part2': item.get('part2') + this.counter++
});
this.collection.add(item);
},
appendItem: function(item){
var itemView = new ItemView({
model: item
});
$('#list', this.el).append(itemView.render().el);
},
render: function(){
$(this.el).append("<button id='add'>Add Item</button>");
$(this.el).append("<ul id='list'></ul>")
},
});
var Tasker = new AppView();
})(jQuery);
从上面的代码中我无法理解一件事。在函数appendItem
中有这段代码:
itemView.render().el
任何人都可以解释我为什么render()
使用该部分调用该函数.el
,为什么不只是itemView.render()
?
感谢您的时间和帮助:-)