Skip to content

Instantly share code, notes, and snippets.

@lancejpollard
Forked from thehydroimpulse/adapter.js
Created February 2, 2013 00:59
Show Gist options
  • Save lancejpollard/4695368 to your computer and use it in GitHub Desktop.
Save lancejpollard/4695368 to your computer and use it in GitHub Desktop.
(function () {
'use strict';
var next_id, Context;
next_id = 1;
Context = function () {
this.id = next_id++;
this.invalidateBindings = [];
};
Context.current = null;
Context.prototype.onInvalidate = function(cb) {
this.invalidateBindings.push(cb);
};
Context.prototype.invalidate = function() {
var id;
for (id in this.invalidateBindings) {
if (this.invalidateBindings.hasOwnProperty(id)) {
this.invalidateBindings[id]();
}
}
};
_.extend(Context.prototype, {
run: function(cb) {
var previous = Context.current;
Context.current = this;
try {
return cb();
} finally {
Context.current = previous;
}
}
});
module.exports = Context;
}());
(function() {
var ContextSet = function() {
this._set = {};
};
ContextSet.prototype.add = function(ctx) {
if (ctx && ctx instanceof Context) {
var self = this;
if (ctx && ! (ctx.id in self._set)) {
self._set[ctx.id] = ctx;
ctx.onInvalidate(function() {
delete self._set[ctx.id];
});
}
return true;
}
return false;
};
ContextSet.prototype.addCurrentContext = function() {
var context = Context.current;
if (! context) {
return false;
}
return this.add(context);
};
ContextSet.prototype.invalidateAll = function() {
for (var id in this._set) {
this._set[id].invalidate();
}
};
module.exports = ContextSet;
}());
App.reactive(function(){
console.log("Notification Count: " + App.Notification.all().count());
});
(function() {
var reactive = function (cb) {
// Create a new context;
var context = new Context();
// When the context is invalidated, re-run the whole reactive setup:
context.onInvalidate(function(){
reactive(cb);
});
// Run the context;
context.run(function(){
cb();
});
};
module.exports = reactive;
}());
(function(){
var Session = function() {
this.keys = {};
this.deps = {};
this.keys['hello'] = "Giv";
};
Session.prototype.set = function(key, value) {
this.keys[key] = value;
var invalidateAll = function(ctx) {
ctx && ctx.invalidateAll();
};
invalidateAll(this.deps[key]);
};
Session.prototype.get = function(key) {
if (this.deps[key] != null) {
this.deps[key].addCurrentContext();
} else {
this.deps[key] = new ContextSet();
this.deps[key].addCurrentContext();
}
return this.keys[key];
};
module.exports = Session;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment