Meteor.autorun

This commit is contained in:
David Greenspan
2012-09-16 04:07:49 -07:00
parent d07c760a0d
commit fb765dd5f3
2 changed files with 31 additions and 27 deletions

View File

@@ -137,32 +137,6 @@ Template.timer.destroyed = function () {
///////////////////////////////////////////////////////////////////////////////
// Run f(). Record its dependencies. Rerun it whenever the
// dependencies change.
//
// Returns an object with a stop() method. Call stop() to stop the
// rerunning.
//
// XXX this should go into Meteor core as Meteor.autorun
var autorun = function (f) {
var ctx;
var slain = false;
var rerun = function () {
if (slain)
return;
ctx = new Meteor.deps.Context;
ctx.run(f);
ctx.on_invalidate(rerun);
};
rerun();
return {
stop: function () {
slain = true;
ctx.invalidate();
}
};
};
Template.d3Demo.left = function () {
return { group: "left" };
};
@@ -230,7 +204,7 @@ Template.circles.rendered = function () {
if (! self.handle) {
d3.select(self.node).append("rect");
self.handle = autorun(function () {
self.handle = Meteor.autorun(function () {
var circle = d3.select(self.node).selectAll("circle")
.data(Circles.find({group: data.group}).fetch(),
function (d) { return d._id; });

View File

@@ -1,5 +1,7 @@
(function () {
////////// Meteor.deps.ContextSet
// Constructor for an empty ContextSet.
//
// A ContextSet is used to hold a set of Meteor.deps.Contexts that
@@ -51,4 +53,32 @@
};
Meteor.deps.ContextSet = ContextSet;
////////// Meteor.autorun
// Run f(). Record its dependencies. Rerun it whenever the
// dependencies change.
//
// Returns an object with a stop() method. Call stop() to stop the
// rerunning. Also passes this object as an argument to f.
Meteor.autorun = function (f) {
var ctx;
var slain = false;
var handle = {
stop: function () {
slain = true;
ctx.invalidate();
}
};
var rerun = function () {
if (slain)
return;
ctx = new Meteor.deps.Context;
ctx.run(function () { f.call(this, handle); });
ctx.on_invalidate(rerun);
};
rerun();
return handle;
};
})();