1

I have following code in JavaScript. I would like to execute some logic when any property in the object sizeLogic is changed. Specifically, I would like to change all other properties to false, when any one of these properties is set to true.

Question: How would I achieve this? I am not sure if this is even possible in JavaScript without writing methods like set_leftTop(x), so that within the method we could write the custom logic.

var sizeLogic = {
     leftTop: true,
     leftBottom: false,
     rightTop: false,
     rightBottom: false
}
joyBlanks
  • 6,066
  • 1
  • 19
  • 44
Sunil
  • 19,514
  • 27
  • 103
  • 185

1 Answers1

1

You may find object.watch useful depending on your browser support matrix.

From the MDN:

Warning: Generally you should avoid using watch() and unwatch() when possible. These two methods are implemented only in Gecko, and they're intended primarily for debugging use. In addition, using watchpoints has a serious negative impact on performance, which is especially true when used on global objects, such as window. You can usually use setters and getters or proxies instead

See: Listening for variable changes in JavaScript or jQuery

Community
  • 1
  • 1
Jonathan.Brink
  • 21,521
  • 16
  • 66
  • 107
  • Is this cross-browser compatible? – Sunil Sep 09 '15 at 17:41
  • 1
    No. You may need to come up with a custom solution like shown in the linked SO post: https://gist.github.com/eligrey/384583 – Jonathan.Brink Sep 09 '15 at 17:42
  • Ok. I hope I can use some cross-browser approach that is built-in for JavaScript. – Sunil Sep 09 '15 at 17:43
  • I think its best to use methods for properties. So for leftTop, use set_leftTop and in the set method, all other properties can be set to false. This would work across all browsers. – Sunil Sep 09 '15 at 18:11