PDA

View Full Version : Model with Magic Get Set



bernex
18 Aug 2011, 9:23 PM
I have a simple addition for Ext.data.Model

Using:


var user = new User();

user.setName("Cola");
user.setCompanyTitle("New Company");

console.debug(
user.getName(), // alias for user.get("name") or user.get("Name")
user.getCompanyTitle() // alias for user.get("company_title") or user.get("CompanyTitle")
);

user.save();


Definition:


Ext.define("Bnx.data.Model", {
extend:"Ext.data.Model",

mixins: {
magicGetSet: 'Bnx.data.MagicGetSet'
},

// magicNameConvert: false,

.......

constructor:function() {
var me = this;

me.callParent(arguments);

me.mixins.magicGetSet.constructor.call(me);
}

.........
});


or



Ext.define("Bnx.data.MagicGetSet", {
extend:"Ext.data.Model",
// magicNameConvert: false,
.........
});


Class:


Ext.define("Bnx.data.MagicGetSet", {
magicNameConvert: true,

constructor: function(config) {
var me = this;

me.callParent(arguments);

me.fields.each(function(field) {
var fieldName = field.name;

if(me.magicNameConvert) {
fieldName = me.underlineToCapitalize(fieldName);
}

me["get"+fieldName] = Ext.bind(me.get, me, [fieldName]);
me["set"+fieldName] = function(value) {
me.set(fieldName, value);
};
});
},

underlineToCapitalize: function(str) {
str = str.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
return str.split("_").join("");
}
});