Skip to content

Commit

Permalink
Specify context for onComplete.
Browse files Browse the repository at this point in the history
It seems to be a nice feature that the oncomplete method be allowed to
have a specific context within which to execute (GH-47).

Signed-off-by: Nick Campbell <nicholas.j.campbell@gmail.com>
  • Loading branch information
ncb000gt committed Sep 11, 2012
1 parent f58efd6 commit 41bd4f3
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/cron.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,18 +231,20 @@ CronTime.prototype = {



function CronJob(cronTime, onTick, onComplete, start, timeZone) {
function CronJob(cronTime, onTick, onComplete, start, timeZone, context) {
if (typeof cronTime != "string" && arguments.length == 1) {
//crontime is an object...
onTick = cronTime.onTick;
onComplete = cronTime.onComplete;
context = cronTime.context;
start = cronTime.start;
timeZone = cronTime.timeZone;
cronTime = cronTime.cronTime;
}

if (timeZone && !(CronDate.prototype.setTimezone)) console.log('You specified a Timezone but have not included the `time` module. Timezone functionality is disabled. Please install the `time` module to use Timezones in your application.');

this.context = (context || this);
this._callbacks = [];
this.onComplete = onComplete;
this.cronTime = new CronTime(cronTime, timeZone);
Expand Down Expand Up @@ -270,7 +272,7 @@ CronJob.prototype = {
for (var i = (this._callbacks.length - 1); i >= 0; i--) {

//send this so the callback can call this.stop();
this._callbacks[i].call(this, this.onComplete);
this._callbacks[i].call(this.context, this.onComplete);
}
},

Expand Down
38 changes: 38 additions & 0 deletions tests/test-cron.js
Original file line number Diff line number Diff line change
Expand Up @@ -361,5 +361,43 @@ module.exports = testCase({
});
assert.done();
}, 1250);
},
'test cronjob scoping': function(assert) {
assert.expect(2);
var c = new cron.CronJob('* * * * * *', function() {
assert.ok(true);
assert.ok(c instanceof cron.CronJob);
}, null, true);
setTimeout(function() {
c.stop();
assert.done();
}, 1250);
},
'test non-cronjob scoping': function(assert) {
assert.expect(2);
var c = new cron.CronJob('* * * * * *', function() {
assert.ok(true);
assert.equal(this.hello, 'world');
}, null, true, null, {'hello':'world'});
setTimeout(function() {
c.stop();
assert.done();
}, 1250);
},
'test non-cronjob scoping inside object': function(assert) {
assert.expect(2);
var c = new cron.CronJob({
cronTime: '* * * * * *',
onTick: function() {
assert.ok(true);
assert.equal(this.hello, 'world');
},
start: true,
context: {hello: 'world'}
});
setTimeout(function() {
c.stop();
assert.done();
}, 1250);
}
});

0 comments on commit 41bd4f3

Please sign in to comment.