Ayyoudy
Ayyoudy

Reputation: 3721

dojo: how to clone widgets?

How do I go about cloning a Dojo form (dijit.form.Form) with its child widgets? Ideally, i'd like to change the Id's of the clone widgets as well. I also would be interested in cloning any events that might be attached to the widgets.

I played a bit with dojo.clone but that only works for DOM objects.

Thanks

Upvotes: 1

Views: 1875

Answers (1)

fncomp
fncomp

Reputation: 6178

Assuming inheritance is really what you need, then I'd just make a new widget. Assuming you are using the async loader and Dojo 1.7. I'd do something like:

define([
    'dojo',
    'module',
    'dijit/form/Form',
    'dijit/form/TextBox',
    'dijit/_TemplatedMixin',
    'dijit/_WidgetsInTemplatedMixin'
], function (dojo, module, Form, TextBox, _TemplatedMixin, _WidgetsInTemplatedMixin) {
    // I have a wrapper for declare that handles this, but...
    return dojo.declare(module.id.replace(/\//g, '.'), [Form, _TemplatedMixin, _WidgetsInTemplatedMixin], {

        widgetsInTemplate: true,

        // Make a template, I usually use a separate file.
        templateString: '<form data-dojo-type="dijit.form.Form">' +
                             '<input data-dojo-type="dijit.form.TextBox" />' +
                        '</form>'

        postCreate: function () {
            this.inherited(arguments);
            // Attach your specialized events.
        }
    });
});

If you're using the sync loader, then you'll want dojo.declare:

dojo.provide('mynamespace.CustomForm');

// Do this for all child widgets and anything else you use.
dojo.require('dijit.form.Form'); 
dojo.require('dijit._Templated');
dojo.require('dijit.form.TextBox');

dojo.declare('mynamespace.CustomForm', [dijit.form.Form, dijit._Templated], {

        widgetsInTemplate: true,

        // Make a template, I usually use a separate file.
        templateString: '<form dojoType="dijit.form.Form">' +
                             '<input dojoType="dijit.form.TextBox" />' +
                        '</form>'

        postCreate: function () {
            this.inherited(arguments);
            // Attach your specialized events.
        }
    });
});

Your module will then be available with var container = someElement; new path.to.File({}, container);. Or you could declare the widget in your markup. Let me know if I can make this more specific or apply to different versions of Dojo.

Upvotes: 2

Related Questions