2013년 10월 17일 목요일

Advanced functionality with plugins

var form = Ext.create('Ext.form.Panel', {
renderTo: Ext.getBody(),
bbar: [{
xtype: 'button',
text: 'Edit'
}, {
xtype: 'button',
text: 'Save'
}, {
xtype: 'button',
text: 'Cancel'
}],
items: [{
xtype: 'textfield',
fieldLabel: 'Email Address'
}]
});

1. Plugins are simply classes, in the same way that all components are, so we start
by defining our Ext.ux.ReadOnlyField class that will, by default, extend the
Ext.Base class:
Ext.define('Ext.ux.ReadOnlyField', {
});

2. The next step is to define our plugin's init method, which is the starting point
of every plugin. To start with, we simply cache a reference to the plugin's parent
component (that is, the text field) so we can easily access it later:
Ext.define('Ext.ux.ReadOnlyField', {
init: function(parent){
this.parent = parent;
}
});

3. We will use the parent component's render event to create our plugin's extra
markup. We attach a handler method that creates a new DIV element inside
the field's body element:
Ext.define('Ext.ux.ReadOnlyField', {
init: function(parent){
this.parent = parent;
this.initEventHandlers();
},
initEventHandlers: function(){
this.parent.on({
render: this.onParentRender,
scope: this
});
},
onParentRender: function(field){
field.displayEl = Ext.DomHelper.append(field.bodyEl, {
tag: 'div',
style: {
height: '22px',
"line-height": '18px',
margin: '2px 0 0 5px'
}
}, true).setVisibilityMode(Ext.Element.DISPLAY);
field.inputEl.setVisibilityMode(Ext.Element.DISPLAY);
}
});

4. We now add three methods, which will switch between read-only and edit modes.
These methods show and hide the appropriate elements and set the values of them
as needed:
...
edit: function(){
if(this.rendered){
this.displayEl.hide();
this.inputEl.show();
this.cachedValue = this.getValue();
}
},
save: function(){
if(this.rendered){
this.displayEl.update(this.getValue());
this.displayEl.show();
this.inputEl.hide();
}
},
cancel: function(){
if(this.rendered){
this.setValue(this.cachedValue);
this.displayEl.show();
this.inputEl.hide();
}
}
...

5. In order for these methods to be called from the field directly we create a reference to
them in the field's class inside the init method:
init: function(parent){
this.parent = parent;
this.initEventHandlers();
this.parent.edit = this.edit;
this.parent.save = this.save;
this.parent.cancel = this.cancel; }

6. We can now add handlers to our three toolbar buttons to call the relevant method:
...
bbar: [{
xtype: 'button',
text: 'Edit',
handler: function(){
form.items.get(0).edit();
}
}, {
xtype: 'button',
text: 'Save',
handler: function(){
form.items.get(0).save();
}
}, {
type: 'button',
text: 'Cancel',
handle: function(){
form.items.get(0).cancel();
}
}]
...
7. Finally, we attach the plugin to our text field by creating a new plugin instance and
including it in the field's plugins array:
{
xtype: 'textfield',
fieldLabel: 'Email Address',
plugins: [Ext.create('Ext.ux.ReadOnlyField')]
}




댓글 없음:

댓글 쓰기