having fun with code

Setters & Getters on Mootools classes

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?

Related Posts:

1 Comment to Setters & Getters on Mootools classes

  1. Diogo's Gravatar Diogo
    July 14, 2011 at 13:18 | Permalink

    Thank you!

    Helped a lot!

1 Trackback to Setters & Getters on Mootools classes

  1. By on April 14, 2011 at 06:54

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType

About the blog

This is a blog about development, focused mainly on Javascript but also other languages like python, shell scripts and more.

About the author

Eneko Alonso is a software engineer and UI developer with more than eight years of experience in software and web development. He lives in San Luis Obispo, California and works at LEVEL Studios.

Contact Info

Contact Info

PromoteJS

JavaScript JS Documentation