Search code examples
javascriptextjsextjs4

How to initialize object properly and start from clean slate?


I've got this class:

Ext.define('Customer_Portal_UI.FormParameters', {
constructor: function (c) {
    Ext.each(this.ParticipantFormParameters, function (field) {
        if (field.toFieldSet != null) {
            var fieldSetName = c.targetFieldSetPrefix + field.toFieldSet;
            field.toFieldSet = fieldSetName;
        }
    });
},
ParticipantFormParameters: [
    { name: 'service_executive_account_Number', visible: false },
    { name: 'firstname', visible: true, displayText: 'Firstname', toFieldSet: 'GeneralInfoFS', allowBlank: false },
    { name: 'lastname', visible: true, displayText: 'Lastname', toFieldSet: 'GeneralInfoFS', allowBlank: false },
    { name: 'gendercode', visible: true, hasCheckbox: true, displayText: 'Gender', toFieldSet: 'GeneralInfoFS', xtype: 'combo', allowBlank: false },
]
});

If I do this once:

var formParams = Ext.create(Customer_Portal_UI.FormParameters, { targetFieldSetPrefix: 'add' });
console.log(formParams.ParticipantFormParameters[0].toFieldSet);

I will get addGeneralInfoFS.

But if I create this object many times, I'll get addGeneralInfoFS, addaddGeneralInfoFS, addaddaddGeneralInfoFS

What is going on here ? I tried delete formParams but when I initialize an object if the same type again, same problem.

Is it ExtJS or a javascript problem ? I find it weird I need to put effort into simply destroying objects...

EDIT: Ah! I found this in the documentation:

When placing items in the prototype of the prototype, they will be shared across all instances of the class. Unless you specifically want to do this, you should only put "primitive" types inside the prototype definition.

The question now is how to I declare members without them being "in the prototype" ? That's nice, but where does ParticipantFormParameters go exactly then ? I don't want it in the config cause it's dirty, I'll have to drag this huge (the real code has much more items in the array) block of javascript markup everytime I initialize the object ?

I've refactored things in my application with this approach and I'm completely paralized until this works...I cannot unrefactor...

Thank you.


Solution

  • Why do you modify the property ? Use two different variables. This could be the solution :

     (...)
      Ext.each(this.ParticipantFormParameters, function (field) {
            if (field.toFieldSet != null) {
                var fieldSetName = c.targetFieldSetPrefix + field.toFieldSetRaw;
                field.toFieldSet = fieldSetName;
            }
        });
    },
    ParticipantFormParameters: [
        { name: 'service_executive_account_Number', visible: false },
        { name: 'firstname', visible: true, displayText: 'Firstname', toFieldSetRaw: 'GeneralInfoFS', allowBlank: false },