Complex objects in classes

| | Comments (0)


When using Ext.extend to create your own classes, it's critical to understand that complex objects defined outside of a function definition are added to the prototype of the extended class, and as such are shared across all instances of the class. This sharing is not the case with simple attributes.

The solution is to define complex objects inside the "initComponent" function, referencing them via "this".



Ext.BLANK_IMAGE_URL = 'lib/ext/resources/images/default/s.gif';

Ext.onReady(function() {
        Ext.QuickTips.init();

    // This class definition is broken for most uses - the 'obj' complex object is 
    // created when the class is defined, and as such is shared across all instances
    // of the class! Confusingly, 'simple' class attributes are /not/ shared.

        BrokenClass = Ext.extend(Ext.Panel, {
                    obj: {
                        colour: 'red'
                    },
                    simple: 'one', // this is not shared

                    initComponent: function() {
                        BrokenClass.superclass.initComponent.apply(this, arguments);
                    }
                });


    // This class definition is not broken - the 'obj' complex object is created when an 
    // instance of the class is created, and thus is unique to each instance.

        WorkingClass = Ext.extend(Ext.Panel, {
                    initComponent: function() {
                        this.obj = {
                            colour: 'red'
                        };
                        WorkingClass.superclass.initComponent.apply(this, arguments);
                    }
                });



    // Note that b1 and b2 share the value of 'obj', but do NOT share the value 
    // of 'simple'

        var b1 = new BrokenClass();
        var b2 = new BrokenClass();

        b2.obj.colour = 'blue';
        b2.simple = 'two';

        console.log(b1.obj.colour, b2.obj.colour, b1.simple, b2.simple);


        // Note that w1 and w2 each have their own values for 'obj'

        var w1 = new WorkingClass();
        var w2 = new WorkingClass();

        w1.obj.colour = 'blue';

        console.log(w1.obj.colour, w2.obj.colour);
    });

Leave a comment

About this Entry

This page contains a single entry by Bill Hutten published on November 2, 2009 10:10 PM.

GridPanel from JSON data was the previous entry in this blog.

Enabling event bubbling for all items in a class is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Categories

Pages

Powered by Movable Type 4.1