Phonegap + Backbone + jquery mobile。我的骨干模型看起来像(删除了一些代码)
var Purchase = Backbone.Model.extend({
defaults: function() {
return {
name: "",
desc: "",
shopping: null,
price:null,
quantity:1,
createdAt: new Date().getTime(),
modifiedAt: new Date().getTime()
};
}
});
var PurchaseList = Backbone.Collection.extend({
model: Purchase,
comparator: 'name'
});
var ShoppingList = Backbone.Model.extend({
defaults: function(){
return {
name:"",
totalPrice: 0,
createdAt: new Date().getTime(),
modifiedAt: new Date().getTime(),
products: new PurchaseList()
};
}
});
更新购买逻辑重新计算 ShoppingList 的 totalPrice
save: function(position){
var data = this.$el.find("form").serializeObject();
var price = parseFloat(data.price);
var quantity = parseFloat(data.quantity);
var product = new Purchase(data);
product.on('invalid', this.showError);
var shopping = GlobalShopping.findWhere({id: data.shopping});
if(!isNaN(price) && !isNaN(quantity))
shopping.set('totalPrice', shopping.get('totalPrice') + price * quantity);
if(!isNaN(price))
product.set('price', price);
else
product.unset('price');
if(!isNaN(quantity))
product.set('quantity', quantity);
if(this.model.id){
var oldProduct = shopping.get('products').findWhere({id: this.model.id});
if(oldProduct.get('price') != null)
shopping.set('totalPrice', shopping.get('totalPrice') - oldProduct.get('price') * oldProduct.get('quantity'));
product.id = this.model.id;
product.save({}, { success: function(){
shopping.get('products').add([product], {merge: true});
shopping.save({}, {success: function(){ // <<<< issue here
window.app_router.navigate('#shopping/' + data.shopping, {replace: true, trigger: true});
}});
}});
} else {
shopping.get('products').create(product, {wait: true, success: function(){
shopping.save({}, {success: function(){
window.app_router.navigate('#shopping/' + data.shopping, {replace: true, trigger: true});
}});
}, error: function(model, xhr, options){
alert(JSON.stringify(product.toJSON()));
}});
}
}
此代码在 android 4.x 上完美运行,但在没有 PUT 请求的情况下触发 android 2.x 成功事件(由服务器日志检查)。