我刚开始使用 Backbone。根据下面的代码,我有两个问题要问。
第一个问题是在我填写表格并单击按钮后,应该使用一些默认属性创建模型对象。但是,console.log 会在我将模型传递给新视图对象之前使用我填写的表单中的最新属性打印模型。
第二个问题是我可以成功地将数据保存到db,但是我的成功回调函数没有被调用。有人可以帮我回答这些问题吗?
var form = document.forms[0];
var RetailerModel = Backbone.Model.extend({
urlRoot: ' retailer.php',
defaults: {
name: 'company-name',
address: 'company-address',
phone: 'company-phone',
icon: 'http://localhost/icon.png'
}
});
var RetailerCollection = Backbone.Collection.extend({
});
var RetailerView = Backbone.View.extend({
className: 'retailer',
template: _.template($('#retailer-template').html()),
initialize: function() {
//this.listenTo(this.model, 'change', this.render);
var obj = {
name: form.name.value,
address: form.address.value,
phone: form.phone.value
};
this.model.set(obj);
//why the successful callback does not work????
this.model.save(null, {success: function(model, response){console.log('successful');}});
},
render: function() {
$('#retailer-list').append(this.$el.html(this.template(this.model.toJSON())));
return this;
}
});
var RetailerViews = Backbone.View.extend({
});
$('#submit').click(function(e){
var retailer_model = new RetailerModel();
console.log(retailer_model); // this prints out the new changed attributes instead of the default ones, why???
var retailer_view = new RetailerView({model: retailer_model});
form.reset();
});