javascript - Interdependent derived attributes in Ampersand? -


i'd create ampersand state representation of vector simultaneously holds information it's polar , rectangular representation.

i.e. user able do:

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

-or-

vector.x = 0 vector.y = 1 console.log vector.angle #=> 90  

can think of way ampersand?

this old question, might need this. right away can think of 1 way this. you'd need make of variables independent , listen changes update other values. you'd define in props of model variables angle, mag, x, y, , attach event listeners in initialize of view or somewhere else each of these variables. example, angle you'd this:

model.on('change:angle', function(model) {     //first, calculate new x , y values. in model have 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 'change' event yet avoid circular dependencies.         });          model.set({             y: new_calculated_y_value         }, {             silent: true         });         //now, once i've set new values, can trigger events.         model.trigger('change:x', model); //this trigger model.on('change:x'), since based on change angle , mag won't change, no circular dependency appear.         model.trigger('change:y', model);     }  }) 

and repeat each of 4 variables (there room optimisation, idea. in order avoid circular dependencies example need make sure once recalculate, example, angle using whatever x, same angle.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -