Home » Articles » Widget introduction » Hello world

Hello world

In the first example, we will create a "Hello world" widget, that simply shows some text. We start by initialising the pax name space:

//  Create the namespace
var pax = pax || {};
pax.widget = pax.widget || {};
pax.widget.hello = pax.widget.hello || {};
You're probably wondering, why the heck do I have to do that? The reason is simply that we want to ensure that the widget is contained within the PAX name space, so we don't pollute the global name space. The "|| {}" bit ensures that we don't define the name spaces twice.
Next we create our init method:
//  "Controller" method
pax.widget.hello.init = function( target, args ) {
    var model = pax.widget.hello.model( target, args );
    pax.widget.init( {
        target: target,
        model: model,
        template: pax.widget.hello.template()
    } ).render();   // This renders the widget
};
As you can see this is a very basic initialisation, and is considered the standard pattern to follow. If we had any events to assign, the init method would do that after the render method was called. Next we create a template for our widget:
//  "View" method
pax.widget.hello.template = function() {
    return "Hello [:= name :]";
};
This will show Hello, followed by the variable name after it. Note: you may want to read the template introduction, to see how templates work. Finally we create our model:
//  "Model" method
pax.widget.hello.model = function( target, args ) {
    return pax.defaultArgs( {
        name: 'world'   // Default the name to 'world', if none is specified
    }, args );
};
This follows the recommended pattern: set any defaults by using pax.defaultArgs method, and then return the object. It should be noted that this particular widget does not keep any state about itself, as we simply initialise and render it straight away.
Read on to see our widget in action!