setup

  • function
can.Construct.prototype.setup  

construct.setup(...args)

A setup function for the instantiation of a constructor function.

Parameters

  1. args {*}

    The arguments passed to the constructor.

Returns

{Array | undefined}

If an array is returned, the array's items are passed as arguments to init. The following example always makes sure that init is called with a jQuery wrapped element:

WidgetFactory = can.Construct.extend({
    setup: function(element){
        return [$(element)]
    }
})

MyWidget = WidgetFactory.extend({
    init: function($el){
        $el.html("My Widget!!")
    }
})

Otherwise, the arguments to the constructor are passed to init and the return value of setup is discarded.

Deciding between setup and init

Usually, you should use init to do your constructor function's initialization. Use setup instead for:

  • initialization code that you want to run before the inheriting constructor's init method is called.
  • initialization code that should run whether or not inheriting constructors call their base's init methods.
  • modifying the arguments that will get passed to init.

Example

This code is a simplified version of the code in can.Control's setup method. It converts the first argument to a jQuery collection and extends the controller's defaults with the options that were passed.

can.Control = can.Construct.extend({
    setup: function(domElement, rawOptions) {
        // set up this.element
        this.element = $(domElement);

        // set up this.options
        this.options = can.extend({},
                              this.constructor.defaults,
                              rawOptions
                             );

        // pass this.element and this.options to init.
        return [this.element, this.options];
    }
});