I have read the docs and looked at the source behind reactivity, but I don’t understand it.
Can someone explain how this works behind the scenes, as it looks like magic to me :).
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
So it’s actually rather straight forward, at a basic level there are 2 types of functions involved:
Functions that create a reactive context (reactive function)
Functions that invalidate a reactive context (invalidating function)
Functions that can do both. (I lied there are 3)
When you call a
reactive functionit creates acontextthat meteor stores globally and to which thereactive functionsubscribes aninvalidationcallback. The function that you pass to a reactive function, or any functions that run from within it, can be aninvalidating functionand can grab the currentcontextand store it locally. These functions can then at any time, like on a db update or simply a timer call, invalidate thatcontext. The originalreactive functionwould then receive that event and re-evaluate itself.Here’s a step by step using meteor functions (note that
Tracker.autorunused to be calledDeps.autorun):contextcontext‘s invalidation eventcontextfor the first time.contextglobally as the currently activecontextreactive functionand aninvalidating functioncontextand associates it internally with the key “name”when these functions return, meteor cleans up the active context global variable
Session.set is another function capable of invalidating a
context.contexts created by Session associated with the key “name”contexts, when invalidated, run their invalidation callbacks.contexts (That’s the design of Session.get and not what a invalidation callback must do)contextsnow run their invalidation callbacks.contextagain.The whole implementation is actually rather straight forward as well, you can see it here:
https://github.com/meteor/meteor/blob/master/packages/tracker/tracker.js
And a good example of how it works can be found here:
https://github.com/meteor/meteor/blob/master/packages/reactive-dict/reactive-dict.js
Reactive programming is not actually meteor or JS specific
you can read about it here: http://en.wikipedia.org/wiki/Reactive_programming