Search code examples
dojowidgetdeclare

Dojo instances of same widgets are not saparated


I have built a Dojo Widget for creating a list by entering values. the widget code is: define(["dojo/_base/declare", "dijit/_WidgetBase", "dijit/_TemplatedMixin", 'dojo/text!apps/orders/templates/multiAddList.html', "dojo/dom", "dojo/on", "dojo/dom-construct", "dojo/dom-class", "dojo/query", "dijit/focus"],

function (declare, WidgetBase, TemplatedMixin, html, dom, on, domConstruct, domClass, query, focusUtil) {

    return declare([WidgetBase, TemplatedMixin], {

        templateString: html,

        postCreate: function () {
            this.inherited(arguments);
            var that = this;
        },

        _checkIfEnter: function (e) {
            if (e.which == 13) {
                this._addUser();
            }
        },

        _addUser: function () {
            domClass.remove(this.ulAdded, "hidden");
            var textToAdd = this.userTextToAdd.value;
            var li = domConstruct.create("li", {}, this.ulAdded);
            domConstruct.create("span", {innerHTML: textToAdd}, li);
            var spanX = domConstruct.create("span", {class: 'icon-x right'}, li);
            this.itemsArray.push(textToAdd);
            this.userTextToAdd.value = "";
            focusUtil.focus(this.userTextToAdd);
            var that = this;
            on(spanX, "click", function () {
                domConstruct.destroy(li);
                that.itemsArray.splice(that.itemsArray.indexOf(textToAdd), 1);
                if (that.itemsArray.length == 0) {
                    domClass.add(that.ulAdded, "hidden");
                }
            });
        },

        itemsArray: []

    });
});

It is all OK. However - when I instantiate it twice on same dialog like this:

allowedDomains = new MultiAddList();
allowedDomains.placeAt(dom.byId('allowedDomains'), 0);
pdlEmails = new MultiAddList();
pdlEmails.placeAt(dom.byId('pdlEmails'), 0);

and then asking for allowedDomains.itemsArray() or pdlEmails.itemsArray() - I get the same list (as if it is the same instance) - althought in the UI presentation - he adds the list items separately and correctly.

Obviously, I am doing something wrong although I followed Dojo examples.

Does anyone know what I should do in order to make it work?

Thanks


Solution

  • When you make a dojo class using declare, object and array members are static, meaning they are shared across instances, so I would suggest doing itemsArray: null and then this.itemsArray = [] in the constructor or postCreate somewhere.

    Everything else looks fine, although I too would have a preference for using hitch, your solution is perfectly fine.