LimeJS Creating Custom Object Inheritance

Since LimeJS uses Google to provide a class structure, we have the ability to define custom sprite objects.  A custom sprite object is a class that inherits from Sprite or some other object.  To setup inheritance, do three things:

  1. Include any necessary related objects using goog.provide
  2. Call the base constructor when creating the class, with a statement like “lime.Sprite.call(this);”
  3. Define the inheritance structure at the end via goog.inherits.

You can see a very simple example below:

  1. goog.provide(‘lb.letterPiece’);
  2. lb.letterPiece = function(letter) {
  3. lime.Sprite.call(this);
  4.     this.letter = letter;
  5.     this.selected = false;
  6.     this.lbl = new lime.Label()
  7.       .setText(this.letter.letter)
  8.       .setFontSize(12)
  9.       .setFontColor(‘#fff’)
  10.       .setFontWeight(700)
  11.       .setFontFamily(‘Impact’);
  12.     this.appendChild(this.lbl);
  13. }
  14. goog.inherits(lb.letterPiece, lime.Sprite);

In this code, you can see that we have a constructor lb.letterPiece, which defines its user interface.  We store some settings in two members of the object (letter and selected), as well as create the label that represents the UI.  Once created, the label is appended to the user interface, similarly to how you would append an object to the DOM in JavaScript.

  1. for (var r = 0; r <= this.rows; r++) {
  2.     for (var c = 0; c <= this.cols; c++) {
  3.         i++;
  4.         var l = lb.generateLetter(this.game); //random letter choice
  5.         var selectedLetter = {
  6.             letter: l.letter,
  7.             mod: l.mod,
  8.             row: r,
  9.             col: c
  10.         }
  11.         var piece = new lb.letterPiece(selectedLetter);
  12.         piece.selected = false;
  13.         this.letterPieces.push(piece);
  14.         this.layer.appendChild(piece);
  15.     }
  16. }

As you can see, we can work with these custom sprites as a normal object, setting its properties and invoking it’s constructor using the new keyword.  A sprite is an object that you would draw to the user interface, and therefore we want to add it to the layer (this.layer is a reference to a lime.Layer that’s added to the user interface already).  And so we can see how we can use the object to render, but also work with an API of sorts.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s