Property Observing with Javascript - Observer Design Pattern

As a personal challenge, I find it good practice to learn new programming languages. Each programming language has it's perk and benefits, but what boggles my mind is how javascript replicates almost all of the great features of other languages, even if its not there by default.

The other day I was studying Objective-C, which is quite a good language. It has the ability of observing property changes that extends NSObject. This feature really is wonderful, and I thought, "man I wish javascript had this feature". As I thought that, I said to myself, "I could probably implement this fairly easily with getters and setter in javascript". Now all that is history, and I did it. I implemented it, I tested it, and I am now going to use it as a foundation for all of my javascript applications.

There are two global objects in by code below, window.child, and a window.parent. In the html it list some data about the parent and the child. I have set up the property observing by using the "observe" method of the objects. The callbacks on these observers update the DOM. So open up your javascript console and have some fun with this html page. Change the last name of the parent and see what happens to the child data, and by consequence the DOM. Its exciting.


  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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
<html>
<head>
<style>
body {
margin: 0;
padding: 0;
font-family: arial;
}

.person {
border-radius: 10px;
}

.child {
background-color:#123456;
color:#fff;
padding:10px;
}

.parent {
background-color:#666;
color:#fff;
padding:10px;
}
</style>
</head>
<body>

<div class="parent">
<h1>Parent</h1>
<p>First Name: <span id="parentFirstName">John</span></p>
<p>Last Name: <span id="parentLastName">Smith</span></p>
<p>Age: <span id="parentAge">28</span></p>
</div>

<div class="child">
<h1>Child</h1>
<p>First Name: <span id="childFirstName">Jane</span></p>
<p>Last Name: <span id="childLastName">Smith</span></p>
<p>Age: <span id="childAge">5</span></p>
</div>

<script>


(function(){


var Event = function (type) {
if (!(this instanceof Event)) {
return new Event(type);
}

var event = this;
event.__defineGetter__("type", function(){return type;});

};


window.makeClassObservable = function (OldClass) {
if (typeof OldClass !== "function"){
throw new Error("Expected a constructor as the first argument.");
}

//Create a new constructor and return it.
var NewClass = function () {
var instance = this;

//Old Class
if (Object !== OldClass) {
OldClass.apply(this, arguments);
}

//Listener object.
var propertyListeners = {};
var changeListeners = [];
instance.Event = Event;

//Emits a property change event, and invokes callbacks.
instance.notifyObservers = function (event) {
if (event instanceof Event && instance.notifyObservers.enabled) {

for (var y = 0 ; y < changeListeners.length ; y++){
changeListeners[y].apply(instance, arguments);
}

var listenerArray = propertyListeners[event.type];
if (listenerArray) {
for (var x = 0; x < listenerArray.length; x++) {
listenerArray[x].apply(instance, arguments);
}
}

}
};

instance.notifyObservers.enabled = true;

//Adds listeners
instance.observe = function (type, callback) {
if (arguments.length === 2){
if (!propertyListeners[type]) {
propertyListeners[type] = [];
}

propertyListeners[type].push(callback);
} else if (typeof type === "function"){
changeListeners.push(type);
}
};

//Emits the property callback once and then removes it for you.
instance.observeOnce = function (type, callback) {
callback = callback || type;

if (arguments.length === 2){
var once = function (e) {
callback.apply(this, arguments);
instance.unobserve(type, once);
};x

instance.observe(type, once);
} else if (arguments.length === 1) {
var once = function(e){
callback.apply(this, arguments);
instance.unobserve(once);
};
instance.observe(once);
}

};

//You can remove all listeners of a specified type or refer to a specific listener to remove.
instance.unobserve = function (type, callback) {
if (callback && typeof type === "string" && propertyListeners[type]) {
var listenerArray = propertyListeners[type];

var index = listenerArray.indexOf(callback);
if (index>-1){
listenerArray.splice(index,1);
}

} else if (typeof type === "function"){
for (var a in propertyListeners){
var index = propertyListeners[a].indexOf(type);
if (index > -1){
propertyListeners[a].splice(index,1);
}
}
index = changeListeners.indexOf(type);
if (index > -1){
changeListeners.splice(index,1);
}
} else if (typeof type === "string" && typeof callback === "undefined") {
propertyListeners[type] = [];
}
};

//This is the object where we store the variable values.
var variables = {};

//For loop wrapped with an instant invocation of an anonomous function to preserve scope.
for (var x in instance) (function (x) {
if (typeof instance[x] !== 'function') {
variables[x] = instance[x];
var hasGetter = instance.__lookupGetter__(x);
var hasSetter = instance.__lookupSetter__(x);

//If it has a getter already, then let the getter handle the response.
if (hasGetter) {
instance.__defineGetter__(x, function () {
return hasGetter.apply(instance, arguments);
});
} else {
instance.__defineGetter__(x, function () {
return variables[x];
});
}

if (hasSetter) {
instance.__defineSetter__(x, function (val) {
var fireEvents = instance.notifyObservers.enabled;
var oldValue = variables[x];
var event = new Event(x);

event.__defineGetter__("newValue", function(){return val;});
event.__defineGetter__("oldValue", function(){return oldValue;});
event.__defineGetter__("property", function(){return x;});
event.target = instance;


if (fireEvents) {
instance.notifyObservers.enabled = false;
};

hasSetter.apply(instance, arguments);
if (fireEvents) {
instance.notifyObservers.enabled = true;
}

//Trigger event
if (oldValue !== val && instance[x]===val) instance.notifyObservers(event);


});
} else {
if (!hasGetter && !hasSetter) {
instance.__defineSetter__(x, function (val) {
var event = new Event(x);
var oldValue = variables[x];
var event = new Event(x);

event.__defineGetter__("newValue", function(){return val;});
event.__defineGetter__("oldValue", function(){return oldValue;});
event.__defineGetter__("property", function(){return x;});

variables[x] = val;
//Trigger event
if (oldValue !== val) instance.notifyObservers(event);

});
}
}
}
})(x);

return instance;
};

var oldClass = new OldClass();
NewClass.prototype = oldClass;

return NewClass;
};


})();


var Person = function(options){
if (!(this instanceof Person)){
return new Person();
}

options = options || {};

this.firstName = options.firstName || "Unknown";
this.lastName = options.lastName || "Unknown";
this.age = options.age || 0;
this.children = options.children || [];
var spouse = null;

this.__defineGetter__("spouse", function(){return spouse});
this.__defineSetter__("spouse", function(val){
if (val instanceof Person){
spouse = val;
}
});

};

window.ObservablePerson = makeClassObservable(Person);

window.parent = new ObservablePerson({
firstName:"John",
lastName:"Smith",
age: 28
});


window.child = new ObservablePerson({
firstName:"Jane",
lastName: "Smith",
age: 5
});

// Now the child automatically changes its last name if the parent does.
parent.observe("lastName", function(e){child.lastName = e.newValue});

// This is where it gets really fun and interesting.

// Listen for the parent to change and update the DOM.
parent.observe("firstName", function(e){
document.getElementById("parentFirstName").innerHTML = e.newValue;
});

parent.observe("lastName", function(e){
document.getElementById("parentLastName").innerHTML = e.newValue;
});

parent.observe("age", function(e){
document.getElementById("parentAge").innerHTML = e.newValue;
});


// Listen for the child to change and update the DOM.
child.observe("firstName", function(e){
document.getElementById("childFirstName").innerHTML = e.newValue;
});

child.observe("lastName", function(e){
document.getElementById("childLastName").innerHTML = e.newValue;
});

child.observe("age", function(e){
document.getElementById("childAge").innerHTML = e.newValue;
});

/*
This observes any changes made to an object. Just pass a callback function without a type.
It will listen for any change made and call the callback.
*/

child.observe(function(e){console.log(e.property + " was changed!");});

/*
To unobserve a global callback, just pass the function to
unobserve. e.g.

var fn = function(){};

//global observe
child.observe(fn);
child.unobserve(fn);

//specific observe
child.observe("firstName", fn);

//Clear like so
child.unobserve(fn);
//Or
child.unobserve(type, fn);
//Or, This one clears all callbacks for that specific property.
child.unobserve(property);

*/


</script>

</body>
</html>

No comments:

Post a Comment