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 :).
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 function
it creates a context
that meteor stores globally and to which the reactive function
subscribes an invalidation
callback. The function that you pass to a reactive function, or any functions that run from within it, can be an invalidating function
and can grab the current context
and store it locally. These functions can then at any time, like on a db update or simply a timer call, invalidate that context
. The original reactive function
would then receive that event and re-evaluate itself.
Here's a step by step using meteor functions (note that Tracker.autorun
used to be called Deps.autorun
):
Tracker.autorun(function(){ alert("Hello " + Session.get("name")); }); Session.set("name", "Greg");
context
context
's invalidation event context
for the first time.context
globally as the currently active context
reactive function
and an invalidating function
context
and 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
.
context
s created by Session associated with the key "name"contexts
, when invalidated, run their invalidation callbacks. context
s (That's the design of Session.get and not what a invalidation callback must do) contexts
now run their invalidation callbacks.context
again.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With