我的简化模型如下所示:
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 时,更改一个属性会更改另一个属性,同时保持相同的纵横比。当我同时更新 x
和 y
时,宽高比会发生变化。我遇到的问题是,当您使用上面的代码对主干模型进行更改时,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;
}
除了 y
值更改为 60 之外,我还不知道 x
值已更改为 50,我的代码更新了 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 });
}
关于javascript - Backbone 模型 .changedAttributes() 未显示所有更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17221680/