Tutorial

Widget Lifecycle

Mendix widgets inherit from dijit._WidgetBase. Read this widget tutorial and the widget documentation to understand the basics of a Dijit widget. For a more in-depth description of the Dijit lifecycle methods, the Dijit Anatomy and Lifecycle chapter from the book Dojo: The Definitive Guide is a good read.

Declaring a widget

Mendix uses the same mechanism as Dojo to declare widgets, but uses a different base class: mxui.widget._WidgetBase:

// A simple Mendix widget.
var HelloWorld = declare(mxui.widget._WidgetBase, {
    message: "Hello world!",

    postCreate: function() {
        // setup your widget here.
    },

    showMessage: function() {
        console.log(this.message);
    }
});

var h = new HelloWorld();
h.showMessage();

Output to console:

Hello world!

As with any Dijit widget, you can inherit from your own widgets:

// A widget inheriting from the widget declared earlier.
declare(mxui.widget.HelloWorld, {
    message: "Specialized hello, world!"
});

var s = new SpecializedHelloWorld();
s.showMessage();

Output to console:

Specialized hello, world!"

Note that the constructor and uninitialize methods are special. Once a widget is instantiated, all constructor methods in the prototype chain will be called. When a widget gets destroyed, all uninitialize methods in the prototype chain will be called.

Mendix specific lifecycle methods

After the widget is constructed, the surrounding widget will pass its context to the update method.

Asynchronous operations inside postCreate()

If your widget needs to wait for some asynchronous operation before it is ready to be put in the DOM, you have to make some changes to your widget:

// A widget which needs to do something asynchronous before it is ready for the DOM.
declare(mxui.widget._WidgetBase, {
    autoLoad: false,
    timeout: 1000,

    postCreate: function() {
        var self = this;

        // Some asynchronous action.  Could also be a runtime request, etc.
        setTimeout(function() {
            self.set("loaded", true);
        }, timeout);
    }
});

The autoLoad property makes the widget itself responsible for indicating that it is ready by setting the attribute loaded to true.