我在API上构建了一个带有主干的前端,并且想知道为什么change
事件不会被触发。提取和保存工作,但模板不会被重新渲染。
集合
var Clients = Backbone.Collection.extend({
url: API.host + '/clients',
model: Client
});
模型
var Client = Backbone.Model.extend({
urlRoot: API.host + '/clients',
defaults: {
clients: {
number: '',
company: '',
address1: '',
address2: '',
city: '',
zip: '',
country: '',
tax: '',
email: '',
phone: ''
}
}
});
查看
var ClientsView = Backbone.View.extend({
id: 'content',
initialize: function() {
// instantiate Collection
this.model = new Clients();
// compile Handlebars template
this.tpl = Handlebars.compile(this.template);
// bind change and reset model events to rerender template
this.model.bind('change', this.render);
this.model.bind('reset', this.render);
},
render: function() {
var self = this;
var obj = this.el;
// get clients and set data to handlebars template
$.when(this.model.fetch()).then(function(response) {
$(obj).html(self.tpl(response));
}, function() {
$(obj).html(self.tpl);
});
return this;
},
events: {
"click #client-save": "save"
},
save: function(e) {
// cache target and parent object for quick form access
var obj = e.target;
var parent = $(obj).closest('#client-modal');
var client = new Client({
clients: {
number: parent.find('[name="number"]').val(),
company: parent.find('[name="company"]').val(),
address1: parent.find('[name="address1"]').val(),
address2: parent.find('[name="address2"]').val(),
city: parent.find('[name="city"]').val(),
zip: parent.find('[name="zip"]').val(),
country: parent.find('[name="country"]').val(),
tax: parent.find('[name="tax"]').val(),
email: parent.find('[name="email"]').val(),
phone: parent.find('[name="phone"]').val(),
web: parent.find('[name="web"]').val()
}
});
client.save();
return false;
}
});
答案 0 :(得分:1)
绑定函数时需要传递上下文。
this.model.bind('change',this.render, this )
尝试为集合实例使用其他名称。
// Example
this.collectionClients = new Clients();
\ 0 /