我想创建一个矢量的“和”状态表示,它同时包含关于它的极坐标和矩形坐标的信息。
也就是说,我希望用户能够:
vector.angle = 90
vector.mag = 1
console.log vector.y #=> 1-或者-
vector.x = 0
vector.y = 1
console.log vector.angle #=> 90 有没有人能想出一种用ampersand做到这一点的方法?
发布于 2016-03-06 06:14:14
这是一个老生常谈的问题,但可能有人需要这个。我马上就能想出一种方法来做到这一点。您需要使所有变量独立,然后侦听更改以更新其他值。因此,您可以在模型变量angle、mag、x、y的props中定义,然后在视图的initialize中或其他地方将事件侦听器附加到每个变量。例如,对于angle,您可以这样做:
model.on('change:angle', function(model) {
//first, calculate new x and y values. In your model you have a new angle value
if (NEW_CALCULATED_X_VALUE != model.x || NEW_CALCULATED_Y_VALUE != model.y) {
model.set({
x: NEW_CALCULATED_X_VALUE
}, {
silent: true//I'm not triggering the 'change' event yet to avoid circular dependencies.
});
model.set({
y: NEW_CALCULATED_Y_VALUE
}, {
silent: true
});
//now, once I've set all new values, I can trigger events.
model.trigger('change:x', model); //this will trigger model.on('change:x'), but since based on this change angle and mag won't change, no circular dependency will appear.
model.trigger('change:y', model);
}
})并对四个变量中的每个变量重复此操作(有优化的空间,但您明白我的想法。为了避免这个例子中的循环依赖,你需要确保一旦你使用任何x重新计算角度,你就会得到相同的角度。
https://stackoverflow.com/questions/35046705
复制相似问题