Syntactic sugar for classes in jide.js

jide.js comes with a simple class framework, jidejs/base/Class, however, you don’t have to use it if you don’t like it.

jidejs/base/Class is quite simple. It helps you to extend from other classes, mix in other objects and define custom methods. Things tend to get ugly when you need to define ObservableProperties, though. Let’s take another look at the previous example, the Switch control (without AMD boilerplate).

function Switch(config) {
  installer(this); // this initializes the observable properties
  Control.call(this, config || {});
  this.classList.add('jide-extra-switch');
}
// Switch extends Control
Class(Switch).extends(Control).def({
  // set the default values for our properties
  checked: false,
  checkedText: '',
  uncheckedText: '',

  // we need to release the properties when the object is released
  dispose: function() {
    installer.dispose();
    Control.prototype.dispose.call(this);
  }
});
// now define the properties and get the installer
var installer = ObservableProperty.install(Switch, 'checked', 'checkedText', 'uncheckedText');

This solution is quite efficient but not very friendly to the eye and also quite a bit to type. Still, if you need to squeeze out the last miliseconds, it’s a good choice to use it.

Now, what if you prefer readability over pure speed? It’s just a few miliseconds anyway, right? Well, jide.js in no way limits you in how you create your classes. Pick any of the famous class frameworks (that are constructor based) and you’re good to go. But wouldn’t it be nice if there was a specialized class framework for jide.js that chooses readability and writability over speed and integrates nicely with ObservableProperty?

Well, now there is: jidejs-extra/Class.

Let’s explore how to create the above Switch class using this new framework:

var Property = Class.Property, // import the Property marker
  Switch = Class({ // define class Switch
  $extends: Control, // extends Control

  // this is the constructor function
  $init: function(config) {
    Control.call(this, config || {});
    this.classList.add('jide-extra-switch');
  },

  // define a property with a default value
  checked: Property({ value: false }),
  // define properties without default value
  checkedText: Property,
  uncheckedText: Property
});

Much more concise, isn’t it? Pick your preferred class framework to work with jide.js. It’s completely up to you.

Leave a Reply

Your email address will not be published. Required fields are marked *