主干模型. changedattributes()没有显示所有的更改

Backbone Model .changedAttributes() not showing all changes

本文关键字:显示 模型 changedattributes      更新时间:2023-09-26

我的简化模型如下:

var model = new Backbone.Model({
  defaults: {
    x: 50,
    y: 50,
    constrain_proportions: true
  },
  initialize: function () {
    // Do stuff to calculate the aspect ratio of x and y
    this.on('change:x', doStuff, this);
    this.on('change:y', doStuff, this);
  },
  doStuff: function () {
    // ...
    if (this.get('constrain_proportions')) {
      var changes = this.changedAttributes();
      // Do stuff to make sure proportions are constrained
    }
  }
});

我遇到了一个问题,我正在做这样的改变:

model.set({
  x: 50,
  y: 60
});

在我的doStuff方法中,我想确保当constrain_proportions设置为true时,改变一个属性,将改变另一个属性,保持相同的宽高比。当我同时更新xy时,长宽比发生了变化。我遇到的问题是,当您使用上面的代码对骨干模型进行更改时,x属性与默认值相同。在Backbone中,这会导致model.changedAttributes()返回:

{ y: 60 }

这是由于Model.set方法中的代码块:

// For each `set` attribute, update or delete the current value.
  for (attr in attrs) {
    val = attrs[attr];
    if (!_.isEqual(current[attr], val)) changes.push(attr);
    if (!_.isEqual(prev[attr], val)) {
      this.changed[attr] = val;
    } else {
      delete this.changed[attr]; // The culprit is right here
    }
    unset ? delete current[attr] : current[attr] = val;
  }

我的代码不知道x的值变为50,y的值变为60,我的代码将x的值更新为60,使其保持模型初始化时设置的1:1长宽比。通过更改{x: 50, y: 60},我想将宽高比更改为5:6,但上面的代码来自Backbone,当值被更改时不会发生这种情况,就像以前一样。

我如何成功地绕过这个?

当我想强制更改事件时,我默默地取消了属性,然后重新设置:

model.unset('x', { silent: true }).unset('y', { silent: true }).set({ x: 50, y: 60 });

为了更方便,您可以将其封装在模型上的另一个函数中:

setXY: function(x, y) {
    this.unset('x', { silent: true }).unset('y', { silent: true }).set({ x: x, y: y });
}