Michael Phelps
Michael Phelps

Reputation: 3591

ExtJS model getters and setters

How to implement getters and setters in Ext.data.Model?

My example:

Ext.define('Person', {
    extend: 'Ext.data.Model',
    fields: [{
        name: 'Name',
        type: 'string'
    }, {
        name: 'Surname',
        type: 'string'
    }, {
        name: 'BirthDate',
        type: 'date',
        dateFormat: 'd-m-Y'
    }, {
        name: 'Salary',
        type: 'int'
    }, {
        name: 'Married',
        type: 'boolean'
    }],
    convert: function (v, record) {
        console.log(v)
        return record.get('Surname') + v;
    }
});

var person = Ext.create('Person', {
    Name: 'Eugene',
    Surname: 'Popov',
    BirthDate: '22-05-1984',
    Salary: 300,
    Married: false
});

console.log(person.get('Salary')); //300

I want for example person.get('Salary') return 300 dollars. Thanks for you help.

Upvotes: 0

Views: 2362

Answers (1)

John Hall
John Hall

Reputation: 1346

As George stated, it is indeed baked into the model for you, however for convenience sake you can add your own getters and setters should you so desire.. Personally I do add a few getters and setters to my models, as it helps clean up code throughout the application. In my opinion model.set('some_long_field_name', data); is rather ugly syntax, but that is just me being nit-picky :) Business logic methods pertaining to the model should also be defined in the model!

Ext.define('Person', {
    extend: 'Ext.data.Model',
    fields: [{
        name: 'Name',
        type: 'string'
    }, {
        name: 'Surname',
        type: 'string'
    }, {
        name: 'BirthDate',
        type: 'date',
        dateFormat: 'd-m-Y'
    }, {
        name: 'Salary',
        type: 'int'
    }, {
        name: 'Married',
        type: 'boolean'
    },{
        name: 'MyComplicatedFieldName',
        type: 'auto'
    }],

    /** If your model represents some server side data, the proxy should be here */
    proxy: { /** ... */ },

    /** You can define your own getters and setters, as well as any other
        methods for handling business logic right here in the model, and you should!
      */

    getCf: function(){
        return this.get('MyComplicatedFieldName');
    },

    setCf: function(value){
        this.set('MyComplicatedFieldName', value);
    }
});

var person = Ext.create('Person', {
    Name: 'Eugene',
    Surname: 'Popov',
    BirthDate: '22-05-1984',
    Salary: 300,
    Married: false,
});

person.setCf({});

console.log(person.getCf()); // Object {}

I hope that helps!

Upvotes: 5

Related Questions