Javascript 主干模型.changedAttributes()未显示所有更改
我的简化模型如下所示:Javascript 主干模型.changedAttributes()未显示所有更改,javascript,backbone.js,Javascript,Backbone.js,我的简化模型如下所示: 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); thi
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
方法中,我想确保当constraint\u-properties
设置为true时,更改一个属性将更改另一个属性,保持相同的纵横比。当我同时更新x
和y
时,纵横比会发生变化。我遇到的问题是,当您使用上面的代码对主干模型进行更改时,x
属性与默认值相同。在主干网中,这会导致model.changedAttributes()
返回:
{ y: 60 }
这是由于模型中的这段代码造成的。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,但上面来自主干网的代码在值更改与以前相同时防止发生这种情况
如何成功绕过此问题?当我想要强制更改事件时,我会以静默方式取消设置属性,然后再次设置:
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 });
}