Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
The HasOne association in ExtJS needs some love - it would be nice if we could specify a 'name', which generates all of the necessary variables following a convention. This makes defining the association a lot less verbose Before and After examples are included.
// Apply an override to the HasOne association, allowing a 'name' parameter to generate the getter, setter, associationKey, and associatedName
Ext.override(Ext.data.association.HasOne, {
constructor: function(config) {
if (config.name ) {
Ext.applyIf(config, {
getterName: 'get' + Ext.String.capitalize(config.name),
setterName: 'set' + Ext.String.capitalize(config.name),
associationKey: config.name,
associatedName: config.name
})
}
this.callParent([config])
}
})
// BEFORE
// A JobPosition has a title (a field), a manager (a person), and an occupant (another person)
Ext.define('JobPosition', {
extend: 'Ext.data.Model',
fields: [
{ name: 'title', type: 'string' }
],
hasOne: [
{ model: 'Person', getterName: 'getManager', setterName: 'setManager', associationKey: 'manager', associatedName: 'manager' },
{ model: 'Person', getterName: 'getOccupant', setterName: 'setOccupant', associationKey: 'occupant', associatedName: 'occupant' }
]
})
// a Person has a first and last name
Ext.define('Person', {
extend: 'Ext.data.Model',
fields: [
{ name: 'first', type: 'string' },
{ name: 'last', type: 'string' }
]
})
// AFTER
// A JobPosition has a title (a field), a manager (a person), and an occupant (another person)
Ext.define('JobPosition', {
extend: 'Ext.data.Model',
fields: [
{ name: 'title', type: 'string' }
],
hasOne: [
{ model: 'Person', name: 'manager' },
{ model: 'Person', name: 'occupant' }
]
})
// a Person has a first and last name
Ext.define('Person', {
extend: 'Ext.data.Model',
fields: [
{ name: 'first', type: 'string' },
{ name: 'last', type: 'string' }
]
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment