-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObservable.js
More file actions
73 lines (67 loc) · 1.54 KB
/
Observable.js
File metadata and controls
73 lines (67 loc) · 1.54 KB
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
'use strict';
/**
* The Observable object maintains a list of observers and sends out an update to all of them when requested.
*/
class Observable
{
observers;
constructor()
{
this.observers = [];
}
/**
* This function takes in a function, registers it as a listener, and invokes it whenever this object's internal state is updated.
* @param {Object} obj is a function that will be added to the list of functions to be notified on update.
*/
registerListener(obj)
{
var found = 0;
if (obj != null)
{
var l = this.observers.length;
for (var i = 0; i < l; i++)
{
if (this.observers[i] == obj)
{
found = 1;
break;
}
}
if (!found)
this.observers.push(obj);
}
}
/**
* This function unregisters a previously registered function as a listener.
* @param {Object} obj is a function that will be removed from the list of functions to be notified on update.
*/
unregisterListner(obj)
{
var found = 0;
var i;
if (obj != null)
{
var l = this.observers.length;
for (i = 0; i < l; i++)
{
if (this.observers[i] == obj)
{
found = 1;
break;
}
}
if (found)
this.observers.splice(i,1);
}
}
/**
* This function notifies all listeners of a change by sending out an update. The update can be anything, but listeners need to know what it is so they know what to expect.
* @param {Object} update is an object containing an update.
*/
notifyListeners(update)
{
var l = this.observers.length;
for (var i = 0; i < l; i++)
this.observers[i](update);
}
};