Beetlejuice
Beetlejuice

Reputation: 4425

Extjs merge objects

I have a super class in my application, that defines an object like this:

Ext.define('superclass', {
    myObject: {
        prop1: true,
        prop2: 200,
        ..
    }

and a child class that inherited the superclass above, that declares the same object:

Ext.define('childclass', {
    extend: 'superclass',

    myObject: {
        prop3: false,
        prop4: false,
        ..
    }

The problem is with that, the myObject in the child class has only the prop3 and prop4 properties.

I need that myObject ib child class has all prop1, prop2, prop3 and prop4 properties.

How can I do this ?

Upvotes: 8

Views: 7477

Answers (3)

Molecular Man
Molecular Man

Reputation: 22386

Extend the object in the constructor (or in initComponent if you extend Ext.Component):

Ext.define('childclass', {
    extend: 'superclass',

    constructor: function() {
        this.myObject = Ext.apply({}, this.myObject, {
            prop3: false,
            prop4: false
        });
        this.callParent(arguments);
    }
});

Demo.

Upvotes: 5

wantok
wantok

Reputation: 995

Both of the provided answers will change the superclass prototype's myObject property as soon as a child class is constructed. This may not be what you want. I question why you are putting an object on the class prototype like this. It's generally not a good idea to do it. But if you really want to, you can do this

Ext.define('childclass', {
    extend: 'superclass',

    // I'm adding an empty object here so that myObject on the
    // prototype does not get overridden.
    myObject: Ext.merge({}, superclass.prototype.myObject, {
        prop3: false,
        prop4: false
    });

});

Upvotes: 3

Johan Haest
Johan Haest

Reputation: 4421

@Molecular man's answer is correct, however I would use the merge function.

Lets say you have this in your first config:

myObject: {
   prop1: false,
   person: {
       name: "John"
   }
}

And your second object

myObject: {
   prop2: false,
   person: {
       surname: "Doe"
   }
}

Your apply will overwrite person and you'll only have person.surname.

Into something like this:

myObject: {
   prop1: false,
   prop2: false,
   person: {
       surname: "Doe"
   }
}

Merge will merge the two objects.

Ext.define('childclass', {
    extend: 'superclass',

    constructor: function() {
        this.myObject = Ext.merge(this.myObject, {
            prop3: false,
            prop4: false
        });
        this.callParent(arguments);
    }
});

Note that this will only be needed in the sitation as described in my example, if not you can use Molecular's answer.

Upvotes: 0

Related Questions