【问题标题】:Backbonejs - Avoid parse after saveBackbonejs - 保存后避免解析
【发布时间】:2013-08-27 04:42:32
【问题描述】:

Backbone documentation 说,

每当服务器返回模型的数据时调用parse,在 获取,并保存。该函数被传递原始响应对象,并且 应该返回要在模型上设置的属性哈希。

但是我为我的模型定制了解析函数。我只想在获取数据时执行它,而不是在保存数据时执行。

有办法吗?我可以在解析函数中检查我的响应。但是有没有内置选项可以做到这一点?

【问题讨论】:

  • 可能重复:here。另请查看this

标签: backbone.js


【解决方案1】:

这是来自主干source file 关于保存模型:

var model = this;
var success = options.success;
options.success = function(resp) {
    model.attributes = attributes;
    var serverAttrs = model.parse(resp, options);
    if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
    if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
        return false;
    }
    if (success) success(model, resp, options);
    model.trigger('sync', model, resp, options);
};

您可以在您的 save 上传递一个自定义选项,例如:model.save(null, { saved: true }),然后在您的自定义 parse 中:

parse: function(response, options) {
    if ( options.saved ) return this.attributes;
    // do what you're already doing
}

我根本没有测试过这个,但它至少应该能让你开始。

【讨论】:

    【解决方案2】:

    只需将 parse:false 作为选项传递给 save 方法即可。

    m = new MyModel()
    s.save(null, {parse: false})
    

    【讨论】:

      猜你喜欢
      • 2012-01-23
      • 2011-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 2011-08-25
      • 1970-01-01
      相关资源
      最近更新 更多