Object.observe is dead. Long live MobX.observe

(Edit 2–3–2016: Mobservable has been rebranded to MobX)

So, ‘Object.observe’ is declared dead. And rightfully so; it’s behavior is too unpredictable. But that doesn’t mean that it is actually a bad idea to have observable objects. Actually, having observable objects is a very powerful concept. So fear not, the MobX library can observe your objects in an efficient manner! And best of all, unlike ‘Object.observe’, it runs on any ES5 environment. It’s API is quite similar to ‘Object.observe’. Seeing is believing, so let’s try it out:

That’s all! ‘observable’ decorates any object you pass into it so that MobX can observe it. From there on you can use ‘observe’ to subscribe to future changes in the object.

How does it work?

Beyond ‘observe’

As you can see, ‘autorun’ is actually a way more powerful concept than ‘observe’. It runs the given function automatically, but only when really needed. It observes deeply. It automatically subscribes to new ToDo’s. And it even unsubscribes from ToDo’s when they are no longer relevant for the function. This is a very powerful concept to keep any kind of derived data automatically and efficiently in sync with data. Things like computed values or even complete user interfaces.

So, if you need to observe complex data structures in a reliable way, just try MobX.

Limitations

  1. Adding a new property to an existing object is not detected automatically. Either declare the property upfront with an ‘undefined’ value, use ‘mobx.extendObservable’ to add the property, or create an observable ES6 like map using ‘mobx.map()’.
  2. Observable arrays aren’t actually arrays but objects instead. They behave just like normal arrays but external libraries might not properly recognize them. In such cases, just ‘.slice()’ the array before passing it to an external library.

Lead Developer @Mendix, JS, TS & React fanatic, dad (twice), creator of MobX, MX RestServices, nscript, mxgit. Created.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store