我刚刚开始使用 Backbone。根据下面的代码,我有两个问题要问。
第一个问题是在我填写表单并单击按钮后,应该使用一些默认属性创建模型对象。但是,在将模型传递给新 View 对象之前,console.log 会打印我填写的表单中具有最新属性的模型。
第二个问题是我可以成功地将数据保存到数据库,但是我的成功回调函数没有被调用。有人可以帮我回答这些问题吗?
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();
});
最佳答案
1 获取模型的正确状态
console.log(retailer_model)
不会显示模型属性,它将显示整个模型,但 console.log(retailer_model.attributes)
会显示。另请记住,console.log
并不总是正确的,特别是如果您在记录后立即修改对象,这可能会导致困惑!
要获取模型的实际当前状态,您应该对其进行浅复制或深复制。因此,您可以使用 underscores clone 而不是 console.log(model)
浅拷贝的方法:
console.log(_(model).clone());
2 保存成功回调
为了提供帮助,我们确实需要更多地了解您的情况。我首先要检查的是您的服务器是否返回正确的反馈。 Backbone 是一个基于 REST 标准的系统。您确定您的服务器返回正确的响应代码吗?如果您使用 Chrome,请打开开发人员工具,然后打开网络选项卡以检查发布模型时收到的响应。为了触发成功回调,服务器应返回状态 200 或 201。
另一种测试方法是查看错误回调是否正在触发:)。
关于javascript - 主干模型保存和回调问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16256635/