10
我從here的backbone.js教程中獲得了這段代碼。代碼如下:Backbone.js render()。el用法
(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()
?
謝謝您的時間,並幫助:-)
感謝您的好回答:-) – Hirvesh