Setters & Getters on Mootools classes

Jul 20 2009 Published by Eneko Alonso under uncategorized

Although I haven’t need them for my classes, I thought it would be very cool to have the possibility to use them. Setters and Getters are very popular in modern programming languages, since they let you do some actions when a member/property of an object is being accessed or modified. Setters and Getters are native on Javascript objects.

  1. // Setter on plain JS
  2. var b = {
  3.   saveCount: 0,
  4.   set count (c) {
  5.     console.log('Setting count (B):' + c);
  6.     this.saveCount = c;
  7.   },
  8.   get count () {
  9.     console.log('count is being accessed (B)');
  10.     return this.saveCount;
  11.   }
  12. }
  13. b.count = 5;
  14. console.log("Count (B): " + b.count);

Well, Mootools objects created using Class do not support that syntax. Fortunately, we can use the __defineSetter__ and __defineGetter__ functions:

  1. // Setter in Mootools
  2. var A = new Class({
  3.   saveCount: 0,
  4.   initialize: function() {
  5.     this.__defineSetter__("count", this.setCount);
  6.     this.__defineGetter__("count", this.getCount);
  7.   },
  8.   setCount: function(c) {
  9.     console.log('Setting count(A):' + c);
  10.     this.saveCount = c;
  11.   },
  12.   getCount: function() {
  13.     console.log('count is being accessed (A)');
  14.     return this.saveCount;
  15.   }
  16. });
  17.  
  18. var a = new A();
  19. a.count = 5;
  20. console.log("Count(A): " + a.count);

Nice, uh?

No responses yet

Sending messages between Javascript objects

Apr 23 2009 Published by Eneko Alonso under uncategorized

When applications (or websites) get pretty big, it usually happens that a lot of different objects or classes interact with each other or, even worst, depend on each other to achieve the site functionality.

A simple example could be a Tabs manager class, which controls a set of tabs in the page. Sometimes, the content in this tabs is sensitive to when the tabs are shown or hidden. At this point you have three options: either the Tabs class needs to know about the content or you create a set of callback functions or you use custom events. Still, for every one of these options you are going to need variables referencing the instances of your classes (this is: var myTabs = new Tabs())

Personally, I don’t like having global variables for the objects I create. I think the code gets very messy and complicated.

So, after dealing with all these issues at work day after day I thought it would be very cool to have a messaging system between my classes, the same way other languages like Cocoa do (in a more simpler way, at least for now).

Sending messages between classes

Wouldn’t it be nice if the Tabs class would send a message every time a new tab is selected? Wouldn’t it be nice if the objects that are going to reside inside those tabs could listen to that message and update accordingly?

To do this, I created a Base class and a Register, where my objects will register automatically upon instantiation (thanks to the Base class).

  1. var InstanceRegister = new Class({
  2.   instances: [],
  3.   addInstance: function(object) {
  4.     this.instances.push(object);
  5.   },
  6.   broadcastMessage: function(msg) {
  7.     $A(this.instances).each(function(item, index) {
  8.       item.processMessage(msg);
  9.     });
  10.   }
  11. });
  12. var Register = new InstanceRegister();
  13.  
  14. var Base = new Class({
  15.   ClassName: 'Base',
  16.   Implements: Options,
  17.   initialize: function(options) {
  18.     this.setOptions(options);
  19.     Register.addInstance(this);
  20.   },
  21.   processMessage: function(msg) {
  22.     console.log(this.ClassName, ' msg received: ');
  23.     console.dir(msg);
  24.   },
  25.   sendMessage: function(msg) {
  26.     Register.broadcastMessage(msg);
  27.   }
  28. });

As you can see, the register is just an array of Instances. Yes, Register is a global object, but it will be the only one we will need. Meanwhile, the Base class adds the new instance to the Register automatically. For convenience, the Base class has a sendMessage method. Also, for convenience, I like to add a ClassName property to all my classes in case I need it later for logging, instance class type identification, etc.

Now, thanks to MooTools, we can create our classes and make them inherit from Base. We can override the processMessages method and act accordingly:

  1. var Tabs = new Class({
  2.  ClassName: 'Tabs',
  3.  Extends: Base,
  4.  …
  5.  activateTab: function(tab) {
  6.   …
  7.   this.sendMessage({msg:'tabActivated', data:tab});
  8.  }
  9. });
  10.  
  11. var VideoPlayer = new Class({
  12.  ClassName: 'VideoPlayer',
  13.  Extends: Base,
  14.  …
  15.  processMessage: function(msg) {
  16.   if (msg.msg == 'tabActivated' && msg.data = 'video-tab') {
  17.    // Play video
  18.   }
  19.  }
  20. });

The beautifulness of this code resides, as I mentioned before, in the absence of any object references. Tabs doesn’t know anything about the VideoPlayer class nor any other object listening to the messages. And the VideoPlayer doesn’t know anything about the Tabs class either. It only knows about the message it has to listen to. No object references, no methods, no callbacks.

Pay attention now. This is the best part! Whenever we instance our classes, no matter how many times we do, we don’t need variable references anymore:

  1. new Tabs();
  2. new VideoPlayer();

Nice, uh?

Since I implemented this class I use it a lot on every project at work. It makes my life easier, keeping my classes simple and independent from each other. It’s even better. We have got to a point where we have integrated this feature with our Flash components, so these send messages to the Register when needed and any JS object listening reacts to them as needed.

By doing this, even being unidirectional (Flash to JS only), we have achieved something great: from now on, our Flash objects don’t need to know anything about our JS objects at all. Just send a message to the register and done.

At any point, even from Firebug, you can send a message to the Register. This is very nice, even for debugging:

  1. Register.broadcastMessage({msg:'hello',data:'world'});

A listener class

I found it is very nice, while in development, to have a Listener class debugging any message received. This way I don’t need to add a console.log call on all my classes to output received messages. The Listener will do it for me:

  1. var Listener = new Class({
  2.  Extends: Base,
  3.  initialize: function() {
  4.   this.parent();
  5.   this.ignoreMessages = false;
  6.  },
  7.  processMessage: function(msg) {
  8.   if (msg.msg == 'stopListener') this.ignoreMessages = true;
  9.   if (msg.msg == 'startListener') this.ignoreMessages = false;
  10.   if (this.ignoreMessages) return;
  11.   console.log('Listener: msg received:');
  12.   console.dir(msg);
  13.  }
  14. });
  15. new Listener();

Even you can control the Listener by sending custom messages to it! Awesome!

Could this be achieved with custom events?

With Mootools, creating custom events is piece of cake. But from what I understand, custom events work only inside the object that is firing them. This is, if object A fires an event ‘customEvent’, you can only listen to it if you add a callback function when you instantiate that class:

  1. var A = new Class({
  2.   Implements: Events,
  3.   initialize: function() {
  4.     document.body.addEvent('click', function() {
  5.       console.log('A: body clicked');
  6.       this.fireEvent('bodyClicked', [this]);
  7.     }.bind(this));
  8.   }
  9. });
  10.  
  11. var B = new Class({
  12.   doSomething: function() {
  13.     console.log('B: doing something…');
  14.   }
  15. });
  16.  
  17. new A({
  18.   onBodyClicked: function() {
  19.     // Tell B to do something (you need a reference to B!)
  20.   }
  21. });
  22. new B(); // Will never do something

Ideally, B should be able to listen to the bodyClicked event without passing any info when A is instantiated. But if I’m not mistaken, this is not possible.

Revised version

I decided that it would be cool to have the Messenger as something my classes could implement, instead of inherit from (Base). Also, it would be good if one object could register for a specific message only, which would improve performance too.

  1. var NotificationServiceCenter = new Class({
  2.  instances: {},
  3.  addObserver: function(msg, instance) {
  4.   if (!this.instances[msg]) {
  5.    this.instances[msg] = [];
  6.   }
  7.   this.instances[msg].push(instance);
  8.  },
  9.  broadcastMessage: function(msg, data) {
  10.   if (this.instances[msg]) {
  11.    $A(this.instances[msg]).each(function(item, index) {
  12.     item.processMessage(msg, data);
  13.    });
  14.   }
  15.  }
  16. });
  17. var NotificationService = new NotificationServiceCenter();
  18.  
  19. var Messenger = new Class({
  20.  addMsgEvent: function(msg) {
  21.   NotificationService.addObserver(msg, this);
  22.  },
  23.  sendMessage: function(msg, data) {
  24.   NotificationService.broadcastMessage(msg, data);
  25.  },
  26.  processMessage: function(msg, data) {
  27.   // For implementation on the final Class
  28.  }
  29. });
  30.  
  31. var A = new Class({
  32.  Implements: Messenger,
  33.  initialize: function() {
  34.   document.body.addEvent('click', function(){
  35.    console.log('A: document body clicked');
  36.    this.sendMessage('documentbodyclicked', 'Hello world!');
  37.   }.bind(this));
  38.  }
  39. });
  40.  
  41. var B = new Class({
  42.  Implements: Messenger,
  43.  initialize: function() {
  44.   this.addMsgEvent('documentbodyclicked');
  45.  },
  46.  processMessage: function(msg, data) {
  47.   console.log('B: msg received: ', data);
  48.  }
  49. });
  50.  
  51. new A();
  52. new B();

Here you go!

2 responses so far

Solving the 8 Queen Puzzle in Javascript

Jan 02 2009 Published by Eneko Alonso under uncategorized

Eight Queens is a classic problem which consist on being able to place 8 queens on a chess board without leaving them in position of eating each other. More info on Wikipedia.

8 Queens
See the 8 Queens demo in action.

On this demo I have created 3 different Mootools classes: ChessBoard, Piece and EightQueen. ChessBoard and Piece are generic classes which I plan to reuse in other demos. EightQueen is the brain of the demo and it inherits from Thread, the class I use for javascript animations. Check the source code at the end of the post.

Solving the problem

The easiest way to solve this problem is using backtracking. Once we find we have 2 queens on eating position, we can cancel that path. Since there can be only one Queen per column, we create an array and store the row on each position. Once the array has 8 items (columns) the problem will be solved.

If we can’t find a valid position for the current column, we need to remove the previous column Queen and add it again in the next row. If there are no more rows, we remove the previous column Queen and so on.

Testing if a position is valid: my solution

So the process to resolve the 8 Queen puzzle is easy after all. But we still need to figure out how to check if a position for a Queen is valid or not. I didn’t want to copy this logic from any other demo or site (I bet there are hundreds of ways to do this). I wanted to think my own way, and this is what I came up:

  1. validPosition: function(position) {
  2.   if (this.queens.indexOf(position.y) != -1) return false;
  3.   for (var index=1, length=this.queens.length; index<=length; index++) {
  4.     var queenY = this.queens[index-1];
  5.     if (position.y + (position.x-index) == queenY) return false;
  6.     if (position.y(position.x-index) == queenY) return false;
  7.   };
  8.   return true;
  9. }

First, we know only one Queen can sit on a column, but also only one Queen can sit on a row. So we check if there is already a Queen in the same row (position.y). If there is one, the position is not valid.

Then, we need to check the diagonals. Queens can move on 45° diagonals. This is, the number of squares the Queen moves is the same in both horizontal and vertical directions. So a position will be invalid if there is a Queen one column away and one row away, or two columns away and two rows away, etc. With a simple equation we can check this. We need to do it twice, since it can be one row before or after. We don’t need to check the columns on the right because we know there are no Queens placed on that side yet (on this demo I am placing Queens from left to right).

Source code

  1. var ChessBoard = new Class({
  2.   pieces: [],
  3.  
  4.   initialize: function(container) {
  5.     this.container = container;
  6.     this.element = new Element('div', {'class': 'board'});
  7.     for (var row=8; row>0; row–) {
  8.       for (var col=1; col<9; col++) {
  9.         var square = new Element('div', {'class': 'square'});
  10.         square.id = "square" + String.fromCharCode(96+col) + row;
  11.         square.addClass(this.isDarkSquare(row,col)?'dark':'light');
  12.         this.element.grab(square);
  13.       }
  14.     }
  15.     this.container.grab(this.element);
  16.   },
  17.  
  18.   isDarkSquare: function(row,col) {
  19.     return ((row%2==0 && col%2==0) || (row%2==1 && col%2==1));
  20.   },
  21.  
  22.   addPiece: function(options) {
  23.     var piece = new Piece(options);
  24.     this.pieces.push(piece);
  25.     this.element.grab(piece.element);
  26.   },
  27.  
  28.   removePiece: function(position) {
  29.     var piece;
  30.     $A(this.pieces).each(function(item) {
  31.       if (item.square.x == position.x && item.square.y == position.y)
  32.         piece = item;
  33.     });
  34.     $A(this.pieces).erase(piece);
  35.     piece.destroy();
  36.   },
  37.  
  38.   removeAll: function() {
  39.     while (this.pieces.length > 0) {
  40.       var piece = this.pieces[this.pieces.length-1];
  41.       piece.destroy();
  42.       this.pieces.length–;
  43.     }
  44.   }
  45. });
  46.  
  47.  
  48. var Piece = new Class({
  49.   Extends: Sprite,
  50.   square: {col:1, row:1},
  51.  
  52.   initialize: function(options) {
  53.     this.options.size = {x:32,y:32};
  54.     this.parent(options);
  55.     this.setFigurine();
  56.     this.moveTo(this.options.square);
  57.   },
  58.  
  59.   setFigurine: function() {
  60.     this.setImage('media/images/icons/chess/'+
  61.             this.options.color + '_' +
  62.             this.options.kind + '_32.png');
  63.   },
  64.  
  65.   moveTo: function(position) {
  66.     if (typeof position == 'string') {
  67.       var parts = position.split("");
  68.       parts[0] = parts[0].charCodeAt(0)96;
  69.       this.square.x = parts[1];
  70.       this.square.y = parts[0];
  71.     }
  72.     else if (position instanceof Object) {
  73.       this.square = position;
  74.     }
  75.  
  76.     this.options.position.x = ((this.square.x-1) * 38) + 3;
  77.     this.options.position.y = ((8-this.square.y) * 38) + 3;
  78.     this.animate(this);
  79.   }
  80. });
  81.  
  82.  
  83. var EightQueens = new Class({
  84.   Extends: Thread,
  85.   queens: [],
  86.  
  87.   initialize: function(options) {
  88.     this.parent(options);
  89.     this.board = new ChessBoard($('content'));
  90.     this.currentRow = Random.get(1,8);
  91.     this.logbox = new Element('div', {'class':'log'}).inject($('content'));
  92.  
  93.     this.chkLog = $('chk-log');
  94.  
  95.     $('btn-restart').addEvent('click', function(){
  96.       this.restart();
  97.     }.bind(this));
  98.   },
  99.  
  100.   execute: function() {
  101.     this.addQueen();
  102.     if (this.queens.length == 8) {
  103.       this.stop();
  104.       this.log('Done.');
  105.     }
  106.   },
  107.  
  108.   addQueen: function() {
  109.     var queenAdded = false;
  110.    
  111.     for (var row=this.currentRow; row<=8; row++) {
  112.       var position = {x:this.queens.length+1, y:row};
  113.  
  114.       if (this.validPosition(position)) {
  115.         this.addToBoard(position);
  116.         queenAdded = true;
  117.         this.currentRow = 1;
  118.         break;
  119.       }
  120.     }
  121.    
  122.     if (!queenAdded) {
  123.       this.currentRow = this.queens[this.queens.length-1] + 1;
  124.       this.board.removePiece({x:this.queens.length,y:this.queens[this.queens.length-1]});
  125.       this.queens.length -= 1;
  126.       if (this.queens.length == 0) this.currentRow = Random.get(1,8);
  127.     }
  128.   },
  129.  
  130.   validPosition: function(position) {
  131.     this.log('Testing position: ' + position.x + ',' + position.y);
  132.     if (this.queens.indexOf(position.y) != -1) return false;
  133.     for (var index=1, l=this.queens.length; index<=l; index++) {
  134.       var queenY = this.queens[index-1];
  135.       if (position.y + (position.x-index) == queenY) return false;
  136.       if (position.y(position.x-index) == queenY) return false;
  137.     };
  138.     return true;
  139.   },
  140.  
  141.   addToBoard: function(position) {
  142.     this.log('Queen added: ' + position.x + ',' + position.y +' – '+ this.queens.toString());
  143.     this.queens.push(position.y);
  144.     this.board.addPiece({kind:'Q', square:position, color:'Yellow'});
  145.   },
  146.  
  147.   log: function(text) {
  148.     if (!this.chkLog.get('checked')) return;
  149.     var p = new Element('p', {'text': text});
  150.     this.logbox.grab(p);
  151.     this.logbox.scrollTop = p.getPosition(this.logbox).y296;
  152.   },
  153.  
  154.   restart: function() {
  155.     this.stop();
  156.     this.queens.length = 0;
  157.     this.board.removeAll();
  158.     this.currentRow = Random.get(1,8);
  159.     this.options.interval = $('field-interval').get('value');
  160.     this.logbox.empty();
  161.     this.start();
  162.   }
  163.  
  164. });
  165.  
  166. window.addEvent('domready', function() {
  167.   new EightQueens({interval: $('field-interval').get('value'), autostart: true});
  168. });

Enjoy!

One response so far