Javascript 符号中相互依赖的派生属性?

Javascript 符号中相互依赖的派生属性?,javascript,coffeescript,state,ampersand.js,Javascript,Coffeescript,State,Ampersand.js,我想创建一个矢量的符号和状态表示法,它同时保存关于它的极坐标和矩形表示法的信息 i、 e.我希望用户能够做到: vector.angle = 90 vector.mag = 1 console.log vector.y #=> 1 -或- 有人能想出一个用安培生来做这件事的方法吗 这是个老问题,但可能有人需要这个。 我马上就可以想出一个办法。您需要使所有变量独立,然后监听更改以更新其他值。因此,您需要在props中定义模型变量angle、mag、x、y,然后在视图的initialize中

我想创建一个矢量的符号和状态表示法,它同时保存关于它的极坐标和矩形表示法的信息

i、 e.我希望用户能够做到:

vector.angle = 90
vector.mag = 1
console.log vector.y #=> 1
-或-


有人能想出一个用安培生来做这件事的方法吗

这是个老问题,但可能有人需要这个。 我马上就可以想出一个办法。您需要使所有变量独立,然后监听更改以更新其他值。因此,您需要在
props
中定义模型变量
angle
mag
x
y
,然后在视图的
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,你就得到了相同的角度

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);
    }

})