/
Event.js
136 lines (117 loc) · 2.72 KB
/
Event.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
/**
* Copyright (c) 2013 Yahoo! Inc. All rights reserved.
*
* Copyrights licensed under the MIT License. See the accompanying LICENSE file
* for terms.
*/
var assert = require('assert');
// Event types
var TYPES = {
NODE_CREATED : 1,
NODE_DELETED : 2,
NODE_DATA_CHANGED : 3,
NODE_CHILDREN_CHANGED : 4
};
/**
* Check if the given event type code is defined or not, throw an error if the
* type is not defined.
*
* @method validateType
* @param type {Number} The type.
*/
function validateType(type) {
assert(typeof type === 'number', 'type must be a number.');
var defined = Object.keys(TYPES).some(function (name) {
return TYPES[name] === type;
});
if (!defined) {
throw new Error('Unknown type: ' + type);
}
}
/**
* Watcher event.
*
* @class Event
* @constructor
* @private
* @param type {Number} The type of the event.
* @param name {String} The name of the event.
* @param [path] {String} The node path of the event.
*/
function Event(type, name, path) {
validateType(type);
assert(
name && typeof name === 'string',
'name must be a non-empty string.'
);
this.type = type;
this.name = name;
this.path = path;
}
/**
* Return the type of the event.
*
* @method getType
* @return {String} The name.
*/
Event.prototype.getType = function () {
return this.type;
};
/**
* Return the name of the event.
*
* @method getName
* @return {String} The name.
*/
Event.prototype.getName = function () {
return this.name;
};
/**
* Return the path of the event.
*
* @method getPath
* @return {String} The path.
*/
Event.prototype.getPath = function () {
return this.path;
};
/**
* Return a string representation of the event.
*
* @method toString
* @return {String} The string representation.
*/
Event.prototype.toString = function () {
var result = this.name + '[' + this.type + ']';
if (this.path) {
result += '@' + this.path;
}
return result;
};
/**
* Factory method to crate an instance of event from an instance of
* jute.WatcherEvent.
*
* @method create
* @param watcherEvent {WatcherEvent} an instance of jute.WatcherEvent
*/
function create(watcherEvent) {
assert(watcherEvent, 'watcherEvent must be a valid object.');
validateType(watcherEvent.type);
var name,
i = 0,
keys = Object.keys(TYPES);
while (i < keys.length) {
if (TYPES[keys[i]] === watcherEvent.type) {
name = keys[i];
break;
}
i += 1;
}
return new Event(watcherEvent.type, name, watcherEvent.path);
}
module.exports = Event;
module.exports.create = create;
Object.keys(TYPES).forEach(function (key) {
module.exports[key] = TYPES[key];
});