Aliaksei Syrel

Pharo-like Announcer in JavaScript

Jan 102015

I like to use Model-View pattern in Pharo to connect UI with its model. For this purpose developers use Announcer class. It's syntax is very simple:

"to subscribe"
self announcer on: OnModelChanged send: #onModelChanged to: self
"to announce"
self announcer announce: OnModelChanged new

In small applications huge frameworks like AngularJS increase complexity and add unnecessary levels of abstractions. When there are only a few models, Model-View pattern helps developer to create simple and compact one-page applications. I propose Announcer implemented in JavaScript. Syntax is almost the same:

// to subscribe
this.announcer().onSendTo(OnModelChanged, this.onModelChanged, this);
// to announce
this.announcer().announce(new OnModelChanged());
// to unsubscribe

Having that JavaScript in browser doesn't support Garbage Collection user should unsubscribe from announcer as soon as View is not used any more. Announcer.unsubscribe(receiver) stands for this.

How to use:

First of all we need to create an Announcement object:

// model announces me when it changes
function OnModelChanged() {}

 Then we create and prototype a Model with single public method doSomething() that just notifies all subscribers about changes: 

function Model () {
   this.announcer = new Announcer();
Model.prototype = (function(){
   return {		
      doSomething : function() {
         this.announcer.announce(new OnModelChanged());

And last but not least we create a view:

function View() {
View.prototype = (function(){
   return {
      setModel : function(aModel) {
         this.model = aModel;
         this.model.announcer.onSendTo(OnModelChanged, this.onModelChanged, this);
      onModelChanged : function(announcement) {
         console.log('model changed!');

Finally let's instantiate and connect our model and a few views:

var model = new Model();
var viewA = new View();
var viewB = new View();



In console there should be:

model changed!
model changed!


It's open source, check out Github repo