Skip to content

Instantly share code, notes, and snippets.

@matb33
Created January 11, 2014 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matb33/8365342 to your computer and use it in GitHub Desktop.
Save matb33/8365342 to your computer and use it in GitHub Desktop.
Reactive async pattern

Example usage:

Template.xyz.value = function () {
  return ReactiveAsync("Template_xyz_value", function (w) {
  	someAsyncFunction(function (result) {
  		w.set(result);
  		w.done();
  	});
  }, {initial: ""});
};
Package.describe({
summary: "Reactive async pattern helper"
});
Package.on_use(function (api) {
api.use([
"deps",
"underscore"
], "client");
api.add_files([
"reactive-async.js"
], "client");
api.export("ReactiveAsync");
});
var store = {};
ReactiveAsync = function (uniqueId, workspace, options) {
uniqueId = uniqueId + (Deps.currentComputation && Deps.currentComputation._id);
var opts = _.extend({
initial: undefined
}, options);
if (!_.has(store, uniqueId)) {
store[uniqueId] = {
dep: new Deps.Dependency,
state: "idle",
val: opts.initial,
newVal: opts.initial
};
}
var o = store[uniqueId];
o.dep.depend();
if (o.state === "idle") {
o.state = "working";
o.newVal = opts.initial;
_.isFunction(workspace) && workspace({
done: function () {
o.state = "done";
this.flush();
},
get: function () {
return o.newVal;
},
set: function (setVal) {
o.newVal = setVal;
},
getCurrent: function () {
return o.val;
},
flush: function () {
o.val = o.newVal;
o.dep.changed();
}
});
}
if (o.state === "done") {
o.state = "idle";
}
return o.val;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment