Using dojo.mixin()

Apr 11, 2007

Sometimes you find yourself needing to union two or more Javascript objects. Dojo provides a handy function called dojo.mixin() that is designed to do just that.

dojo.mixin(object1, object2 [, object3]);

Recently I needed to write a Javascript function that opened a window and attempt to center the window on the screen. I determined that there are 13 parameters that I wanted to support:

  • URL
  • Window name
  • Show scrollbars?
  • Show menubar?
  • Is resizable?
  • Show toolbar?
  • Show location bar?
  • Show status bar?
  • Window size (width, height)
  • Window position (x, y)
  • Centered?

I could have defined my function to accept all 13 arguments, but then every time I want to use it, I need to check the order and make sure everything is correct. Worse yet, if I add a parameter, I need to update each place I use this function.

Instead, I decided it was best to pass in a JSON object that defines only the params I’m interested in setting. And the icing on the cake is the params can be in any order inside the object.

var winParams = {
    url: "http://www.cb1inc.com",
    width: 700,
    height: 500,
    center: true
};

windowOpener(winParams);

Inside my function, I want to perform a mixin of a JSON object containing the default values and the parameters passed in.

dojo.require("dojo.lang.common");

function windowOpener(/*object*/params) {
    var parameters = dojo.mixin(
        {
            name: 'win' + Math.round(Math.random()*10000000),
            scrollbars: true,
            menubar: false,
            resizable: true,
            toolbar: false,
            location: false,
            status: false,
            width: 600,
            height: 400,
            center: false
        },
        params
    );

    // ...
);

Now you can be guaranteed that you have each of the parameters even if they aren’t passed in. What’s better is you can add parameters without updating each place you use this function in your code!


The Dojo Module is an open source Drupal module that enhances Drupal websites with the awesome power of the Dojo Javascript Toolkit.

The project homepage can be found at http://www.cb1inc.com/open-source/dojo-toolkit-module. Take a peek at the documentation and forum to learn more.

Even though 1.0 has just landed, there’s already a roadmap outlining what’s in the pipe. This is a very exciting module that will allow other modules and themes to have highly interactive functionality that Dojo can provide. Stay tuned for more updates and examples!