如何在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美元。 谢谢你的帮助。
答案 0 :(得分:5)
正如乔治所说的那样,它确实已经融入了你的模型中,但是为了方便起见,你可以根据自己的需要添加自己的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 {}
我希望有所帮助!