Skip to content

Instantly share code, notes, and snippets.

@theosp
Created July 10, 2014 06:57
Show Gist options
  • Save theosp/4465c267ef98769591e7 to your computer and use it in GitHub Desktop.
Save theosp/4465c267ef98769591e7 to your computer and use it in GitHub Desktop.
Meteor Deps mechanism
main.js
-------
Deps.autorun(function () { // (7)
Session.get("session_var"); // (1)
});
Session.set("session_var", "x") // (2)
reactive-dict.js
----------------
ReactiveDict = function (migrationData) {
this.keys = migrationData || {}; // key -> value
this.keyDeps = {}; // key -> Dependency
};
.
.
.
// (1)
get: function (key) {
var self = this;
self._ensureKey(key);
self.keyDeps[key].depend(); // (3)
return parse(self.keys[key]);
},
// (6)
_ensureKey: function (key) {
var self = this;
if (!(key in self.keyDeps)) {
self.keyDeps[key] = new Deps.Dependency;
.
.
.
}
},
// (2)
set: function (key, value) {
var self = this;
value = stringify(value);
// If nothing changed return
var oldSerializedValue = 'undefined';
if (_.has(self.keys, key)) oldSerializedValue = self.keys[key];
if (value === oldSerializedValue)
return;
// if changed
self.keys[key] = value;
var changed = function (v) {
v && v.changed(); // (4)
};
changed(self.keyDeps[key]);
.
.
.
},
deps.js
-------
// (3)
depend: function (computation) {
// if computation didn't pass as an argument, try look for
// Deps.currentComputation
if (! computation) {
if (! Deps.active)
return false;
computation = Deps.currentComputation;
}
// add the computation to the list of dependents
var self = this;
var id = computation._id;
if (! (id in self._dependentsById)) {
self._dependentsById[id] = computation;
// When the computation get's invalidated remove it from
// the list of dependents
computation.onInvalidate(function () { // (8)
delete self._dependentsById[id];
});
return true;
}
return false;
},
// (4)
changed: function () {
var self = this;
// invalidate all dependents
for (var id in self._dependentsById)
self._dependentsById[id].invalidate(); // (5)
},
// (5)
invalidate: function () {
var self = this;
if (! self.invalidated) {
// if we're currently in _recompute(), don't enqueue
// ourselves, since we'll rerun immediately anyway.
if (! self._recomputing && ! self.stopped) {
.
.
.
pendingComputations.push(this);
}
self.invalidated = true;
// Call all onInvalidate that got attached to this dep (8)
for(var i = 0, f; f = self._onInvalidateCallbacks[i]; i++) {
Deps.nonreactive(function () {
callWithNoYieldsAllowed(f, self);
});
}
self._onInvalidateCallbacks = [];
}
},
// (7)
autorun: function (f) {
if (typeof f !== 'function')
throw new Error('Deps.autorun requires a function argument');
constructingComputation = true;
var c = new Deps.Computation(f, Deps.currentComputation);
.
.
.
return c;
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment