I have the following object literal being sent to an Ext JS Ext.FormPanel.
This form has a number of form fields , eg "Customer Contact", "Reason for Contact", etc.
Each of these need to be of type dropdown instead a simple text field as they are now.
I converted the first field to a dropdown:
var form_customer_contact = new Ext.FormPanel({
frame:true,
labelWidth: 110,
labelAlign: 'right',
bodyStyle:'padding:0',
width: 300,
height: 600,
autoScroll: true,
itemCls: 'form_row',
defaultType: 'displayfield',
items: [{
fieldLabel: 'Customer Contact',
name: 'customerContact',
allowBlank:false,
value: 'Mr. Smith'
},{
fieldLabel: 'Reason for Contact',
width: 150,
xtype: 'combo',
mode: 'local',
value: '1',
triggerAction: 'all',
forceSelection: true,
editable: false,
fieldLabel: 'Produkt',
name: 'reason',
hiddenName: 'reason',
displayField: 'name',
valueField: 'value',
store: new Ext.data.JsonStore({
fields : ['name', 'value'],
data : [
{name : 'data correction', value: '1'},
{name : 'new contact', value: '2'},
{name : 'missing information', value: '3'}
]
})
}, {
fieldLabel: 'Communication',
name: 'communication',
value: 'test'
}, {
fieldLabel: 'Related Order',
name: 'relatedOrder',
value: 'test'
}, {
fieldLabel: 'Date/Time',
name: 'dateTime',
value: 'test'
}, {
fieldLabel: 'Notes',
name: 'notes',
value: 'test'
}
]
});
Now all the other fields need to be converted to a dropdown as well, but since about 80% of the code will remain the same each, I want to simply call a function , eg like this:
getField('Reason for Contact', 'reason', {'data correction', 'new contact', 'missing information'})
getField('Communication', 'communication', {'telephone', 'fax', 'email'})
What is the best way to create a function or object in Javascript which can be called as described above in order to reduce the code bloat in this example?
You could create a factory function to do that like this:
var createCombo = function(label, name, values) {
var i, data = [];
for(i = 0; i < values.length; i++) {
data.push({ name: values[i], value: i+1+'' });
}
return new Ext.form.ComboBox({
fieldLabel: label,
name: name,
width: 150,
mode: 'local',
value: '1',
triggerAction: 'all',
forceSelection: true,
editable: false,
displayField: 'name',
valueField: 'value',
store: new Ext.data.JsonStore({
fields : ['name', 'value'],
data : data
})
});
};
Then in your list of items call it like this:
createCombo('Reason for Contact', 'reason', ['data correction', 'new contact', 'missing information'])
Extend reusable components by creating xtypes. http://www.sencha.com/learn/Manual:Component:Extending_Ext_Components
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.