Model.x = 0
Model.dependents =
()
everything = 0
first100 = 0
each100 = 0
// Basic example of an infinite loop as an observer (like eToys). function everything() { yield; // Just an idiom because the first yield can not receive a value. while (true) { $("everything").innerHTML = yield; // Get updated X value (now it's hard-coded) }; } Model.addDependent(everything());In this demo. The Model keeps track current mouse X position. And "everything" handler just follow the value. In this case, the handler is just a infinite loop. But the process reaches the point of "yield", it is blocked and wait next changed value. Basically this behavior is same as UNIX's pipe. Or, you can see this is same as eToys process.
// It lives only 100 cycle, after that, the dependency is released automatically. function first100() { yield; for(var i = 0; i < 100; i++) { $("first100").innerHTML = yield; }; } Model.addDependent(first100());This is more interesting one. "first100" handler only handles first 100 updates in the model. It is represented by FOR loop naturally. But if you write this behavior with Observer Pattern, you have to keep a counter somewhere, and after it finish, you need to remove it from dependents list by yourself.
// Only one of 100 is interesting. (because sleep() is difficult in JS) function each100() { yield; while (true) { for (var i = 0; i < 99; i++) yield; // Throw away 99 times! $("each100").innerHTML = yield; } } Model.addDependent(each100());Last example is useful if you don't want every updates.
Both Observer Pattern (MVC) and Polling (Morphic) have each advantage and drawback. If frequency of model's update is slow (like keyboard input), or the timing is critical, Observer Pattern is efficient choice. But if it is very high (like system clock) or there are numbers of observer (like eToys' viewer), Polling is better. And Polling is easier to understand. One motivation is to unify those ideas. The behavior of this demo is same as Observer Pattern, but it can be described like Polling (NOTE: This demo doesn't do anything like a pooling, but I think there is a way to mix those behavior).
Another motivation is to provide a universal event model everywhere. If a program should be a set of independent processes talking each other like Internet. Object dependency should be described same manner. In this demo, you can see each observer as an event handler.
Latest link to the source code http://tinlizzie.org/svn/trunk/jstile/exp/pollingObserver.js
Takashi Yamamiya