dojo.declare secrets
by Nikolai Onken

A very short tuesday morning cookie for the ones who have been starving ;)

When using dojo.declare to build your own fancy widget there is one thing (besides others) you should keep in mind:
Arrays and objects as member variables are stored as references and not copies.

Lets look at a simple example

dojo.declare("calendar", null, {
    month: ["jan", "feb", "mar"],
    getMonth: function(index){
      if (this.month[index]){
        return this.month[index];
      }
    },
    setMonth: function(index, value){
      this.month[index] = value;
    }
});
 
var cal = new calendar();
var cal2 = new calendar();
 
console.log(cal.getMonth(0)); // jan
console.log(cal2.getMonth(0)); // jan
 
cal.setMonth(0, "JAN");
 
console.log(cal.getMonth(0)); // JAN
console.log(cal2.getMonth(0)); // JAN

You see that cal2 has its array changed as well and this is not what you always would like to happen.
To prevent this behavior, all you need to do is setting up a constructor method as following example shows:

dojo.declare("calendar", null, {
    month: [],
    constructor: function(){
      this.month = ["jan", "feb", "mar"];
    },
    getMonth: function(index){
      if (this.month[index]){
        return this.month[index];
      }
    },
    setMonth: function(index, value){
      this.month[index] = value;
    }
});
 
var cal = new calendar();
var cal2 = new calendar();
 
console.log(cal.getMonth(0)); // jan
console.log(cal2.getMonth(0)); // jan
 
cal.setMonth(0, "JAN");
 
console.log(cal.getMonth(0)); // JAN
console.log(cal2.getMonth(0)); // jan

Thats all :)

Tags: ,

This entry was posted on Tuesday, September 2nd, 2008 at 11:37 am and is filed under Dojo Cookies. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “dojo.declare secrets”

  1. rsaccon Says:

    Thanks a lot for this cookie. I was not aware of this fact and I have a custom widget with an object as member and, guess what, a weird behavior (and incredible ugly workaround to make it actually work). Now I can clean things up …

Leave a Reply

You must be logged in to post a comment.