-1

我想使用Backbone.save模型,模型的嵌套数据需要过滤,所以我使用

model.save(null,{
    success: ...,
    error:...,
    data: {
        id:null,
        name:'myname',
        nestmodel: {
            id:'xx'/*Other data i don't need it,so just id column*/
        }
    }
}

而且我不想使用patchHTTP METHOD。因为我只是添加一个新模型,而不是更改零件数据。

而且我不想发布一些nestmodel数据,因为它太大了,我只希望 id 没问题。

nestmodel只需要身份证。

我已阅读同步 (Backbone.js) 和 Backbone.js/express.js 参数时排除模型属性model.save()

有一种方法可以解决这个问题。

这就是我的全部代码:

 sync: function(method, model, options) {
  var data, orderSuiteItems;
  if (method === 'create') {
    options.url = this.url;
  } else {
    // MUST setting the url .options's url is undefined
    options.url = this.url + this.idUrl(this.get('id'));
  }
  // IF `create` or `update` , pick the we need properties
  if (method === 'create' || method === 'update') {
    orderSuiteItems = [];
    if (this.has('orderSuiteItems')) {
      // Because the `dishes` and `dishesUnitPrice` have a lot of prop,
      // Each of `dishes` or `dishesUnitPrice` may each have 10K data
      orderSuiteItems = _.map(this.get('orderSuiteItems'), function(osi) {
        return {
          id: osi.id,
          qty: osi.qty,
          servingQty: osi.qty,
          confirmQty: osi.confirmQty,
          deleted: osi.deleted,
          orderItem: _.pick(osi.orderItem, 'id'),
          dishes: _.pick(osi.dishes, 'id'), // HAVE a large prop 
          dishesUnitPrice: _.pick(osi.dishesUnitPrice, 'id'), // HAVE a large prop 
          orderItemStatus: osi.orderItemStatus,
          piece: osi.piece
        };
      });
    }
    data = {
      id: this.get('id'),
      order: this.get('order'),
      price: this.get('price'),
      dishes: _.pick(this.get('dishes'), 'id', 'isSuite'),
      dishesUnitPrice: _.pick(this.get('dishesUnitPrice'), 'id'),
      qty: this.get('qty'),
      servingQty: this.get('servingQty'),
      confirmQty: this.get('confirmQty'),
      sum: this.get('sum'),
      orderSuiteItems: orderSuiteItems,
      orderItemStatus: this.get('orderItemStatus')
    };
    // Setting attrs with pick data.
    options.attrs = data;
    return Backbone.sync(method, model, options);
  } else {
    return Backbone.sync(method, model, options);
  }
}
4

1 回答 1

-1

我希望您只是data为了示例的清晰起见而选择该选项。

无论如何,在使用unset之前使用删除你的属性怎么样Model#save?稍后重新设置它。
另一种解决方案是覆盖该Model#save方法。
您还可以通过将其定义为属性而不是在原型中来隐藏相同的方法(这将使您有机会切换回来)。

解决方案#1或类似的东西将是最简单的。比方说,解决方案 #2 可能更具风险,但样板文件可能更少。我只会在一些非常具体的情况下使用#3(现在甚至不能考虑一个),其中包括:对象是一个单例(因为我们没有使用原型)(或仅在有限的数量) ,需要大量切换2种模式,最好只有1种方法。

编辑:
解决方案#1:

var nestedModel = myModel.get('nestmodel');
myModel.save('nestmodel', nestedModel.id, {silent: true});
myModel.set('nestmodel', nestedModel, {silent: true});

我添加了silent标志,因为我不知道您是否正在收听nestmodel属性的更改。如果这个不适合您,我将为其他解决方案添加代码。

于 2013-04-20T21:56:25.203 回答