Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Mimmicking Deps.autorun from Meteor in pure Node
"use strict";
var EventEmitter = require('events').EventEmitter;
var Session = new EventEmitter();
Session.data = {};
Session.get = function(key) {
return this.data[key] || null;
};
Session.set = function(key, val) {
this.data[key] = val;
this.emit('change::' + key, val);
};
var Deps = { autorun: null };
// used to be Meteor.autorun
Deps.autorun = function(cb) {
var originalGet = Session.get;
var keysDeps = [];
// mimicking http://docs.meteor.com/#computation_stop
var c = {
stop: function() {
keysDeps.forEach(function() {
Session.removeListener('change::' + key, cb);
});
}
};
Session.get = function(key) {
if (keysDeps.indexOf(key) === -1) {
keysDeps.push(key);
}
Session.on('change::' + key, cb.bind(null, c));
return originalGet.apply(Session, arguments);
};
cb(c);
Session.get = originalGet;
};
// ============================
// The example starts here
// ============================
Session.set('name', 'alex');
Session.set('location', 'Pitesti');
Deps.autorun(function() {
console.log('His name is %s', Session.get('name'));
});
Deps.autorun(function(c) {
var _location = Session.get('location');
var name = Session.get('name');
console.log("%s lives in %s", name, _location);
if (name === 'alexandru') {
console.log('c', c);
c.stop();
}
});
setTimeout(function() {
console.log('=================');
Session.set('name', 'alexandru');
// because of line #63 nothing will be run here
setTimeout(function() {
console.log('=================');
Session.set('location', 'Bucharest now');
}, 1500);
}, 1500);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.