Created
January 18, 2012 15:49
-
-
Save armyofda12mnkeys/1633643 to your computer and use it in GitHub Desktop.
KitchenTimer (Node OOP example)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var KitchenTimer = require('./KitchenTimer'); | |
console.dir(KitchenTimer); | |
console.dir(KitchenTimer.prototype); | |
var timer = KitchenTimer.create(1); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var oop = require('oop'); | |
var EventEmitter = require('events').EventEmitter; | |
var util = require('util'); | |
//console.dir(oop); doesnt have inherits method? | |
function KitchenTimer(properties) { | |
this._interval = null; | |
this._timeout = null; | |
this._minutes = null; | |
this._start = null; | |
EventEmitter.call(this); ///////util.inherits(this, EventEmitter); | |
//oop.mixin(this, properties); | |
} | |
KitchenTimer.SECOND = 1000; | |
KitchenTimer.MINUTE = KitchenTimer.SECOND * 60; | |
KitchenTimer.create = function(minutes) { | |
var timer = new KitchenTimer(); | |
timer.set(minutes); | |
return timer; | |
} | |
KitchenTimer.prototype.set = function(minutes) { | |
var ms = minutes * KitchenTimer.MINUTE; | |
this._timeout = setTimeout(this._ring.bind(this), ms); | |
this._interval = setInterval(this._tick.bind(this), KitchenTimer.SECOND); | |
this._minutes = minutes; | |
this._start = new Date(); | |
}; | |
KitchenTimer.prototype._tick = function() { | |
this.emit('tick'); | |
}; | |
KitchenTimer.prototype._ring = function() { | |
this.emit('ring'); | |
this.reset(); | |
} | |
KitchenTimer.prototype.reset = function() { | |
clearTimeout(this._timeout); | |
clearInterval(this._interval); | |
//oop.reset(this); | |
} | |
KitchenTimer.prototype.remaining = function() { | |
var ms = (new Date() - this._start); | |
var minutes = ms / KitchenTimer.MINUTE; | |
return minutes; | |
}; | |
KitchenTimer.prototype.__proto__ = EventEmitter.prototype; | |
module.exports = KitchenTimer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment