-
Notifications
You must be signed in to change notification settings - Fork 7
/
Accumulator.js
61 lines (52 loc) · 1.73 KB
/
Accumulator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
define(function(require, exports, module) {
var EventHandler = require('famous/core/EventHandler');
var Transitionable = require('famous/transitions/Transitionable');
/**
* Accumulates differentials of event sources that emit a `delta`
* attribute taking a Number or Array of Number types. The accumulated
* value is stored in a getter/setter.
*
* @class Accumulator
* @constructor
* @param value {Number|Array|Transitionable} Initializing value
* @param [eventName='update'] {String} Name of update event
*/
function Accumulator(value, eventName) {
if (eventName === undefined) eventName = 'update';
this._state = (value && value.get && value.set)
? value
: new Transitionable(value || 0);
this._eventInput = new EventHandler();
EventHandler.setInputHandler(this, this._eventInput);
this._eventInput.on(eventName, _handleUpdate.bind(this));
}
function _handleUpdate(data) {
var delta = data.delta;
var state = this.get();
if (delta.constructor === state.constructor){
var newState = (delta instanceof Array)
? [state[0] + delta[0], state[1] + delta[1]]
: state + delta;
this.set(newState);
}
}
/**
* Basic getter
*
* @method get
* @return {Number|Array} current value
*/
Accumulator.prototype.get = function get() {
return this._state.get();
};
/**
* Basic setter
*
* @method set
* @param value {Number|Array} new value
*/
Accumulator.prototype.set = function set(value) {
this._state.set(value);
};
module.exports = Accumulator;
});