Apr 17, 2014

JS OOP with publish/subscribe custom events using jQuery

As the Javascript script grows, traditional programming style will result in messy code. With the help of custom event and OOP, we can keep the code clean, easy to extends and maintain. Below is the snippet comes from my lesson:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
// For testing
function puts(text) {
    document.write("<br>" + text);
}

// Thanks to http://javascript.info/tutorial/all-one-constructor-pattern
function BaseClass() {
 // Private, invisible to child class and outside
 var x;

 // In lost context, using "self" to reference
 var self = this;

 // Public
 this.a = 'a freely property';

 // Public access to restricted var
 this.propertyX = function(_x) {
  if (typeof _x != 'undefined')  x = _x;
  return x;
 }
 this.actionY = function(message) {
  // Bla bla
  // "Publish" an event, pass params as an array
  $(self).triggerHandler('custom_event', [message]);
 }
 $(self).on('custom_event', function(event, message) {
  puts("Base: " + message);
 });
}

function ChildClass() {
 // Inherit, able to have many parents
 BaseClass.apply(this);
 var self = this;
 // To call parent implementation, keep a reference to it
 var parent = { actionY: this.actionY }

 this.actionY = function(message) {
  // Super call, note the params as an array
  parent.actionY.apply(this, [message]);
  // Customize here ...
 }

 this.actionZ = function() { /* Other.. */ }

 $(self).on('custom_event', function(event, message) {
  puts("Extended: " + message);
  puts("With access to: " + self.a);
 });
}

// Now it's time to play with class
c = new ChildClass();
c.propertyX(10);
puts(c.propertyX());
c.actionY('JS OOP is tricky');
</script>

No comments:

Post a Comment

New comment