0

如何在 Ext.data.Model 中实现 getter 和 setter?

我的例子:

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

例如,我想要 person.get('Salary') 返回 300 美元。谢谢你的帮助。

4

1 回答 1

5

正如 George 所说,它确实已为您嵌入到模型中,但是为了方便起见,您可以根据需要添加自己的 getter 和 setter。就我个人而言,我确实在我的模型中添加了一些 getter 和 setter,因为它有助于清理整个应用程序的代码。在我看来model.set('some_long_field_name', data);这是相当丑陋的语法,但这只是我在挑剔:) 与模型有关的业务逻辑方法也应该在模型中定义!

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 {}

我希望这会有所帮助!

于 2013-08-23T14:05:10.053 回答