In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to understand the extension of Ext JS control, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.
Ext JS is a powerful JavaScript library, which can be used to develop RIA (Rich Internet Applications), that is, rich client Ajax applications. It is a front-end Ajax framework independent of background technology.
Ext JS is originally based on YUI (Yahookeeper user Interface Library) technology, developed by developers JackSlocum, and organizes visualization components by referring to mechanisms such as JavaSwing. No matter from the application of CSS style on the UI interface to the exception handling on data parsing, it can be regarded as a very excellent Web development framework.
For most programmers, we don't have any art skills, and many of the company's projects are not equipped with artists, so it's not always easy to develop an eye-catching user interface. However, the emergence of Ext makes it easy to develop a beautiful interface. Ext provides tables, trees, layouts, buttons and many other gorgeous and powerful controls, which saves a lot of time and energy for our daily development work. More importantly, the framework is completely object-oriented and extensible, by modifying the functions of existing libraries or adding new functions to achieve functions that are not available in the Ext framework.
Extend Ext components
Extension is a derived subclass in Ext. Suppose we already have a base class with some methods, and now we want to add new methods. We can use the inheritance feature of the framework and the language feature of JavaScript to create a new class to combine a new class.
Ext provides a mechanism for Ext.extend to implement class inheritance in the Ext framework. This gives you the ability to extend any JavaScript base class without having to modify the code of the class itself, which is an ideal way to extend Ext components.
To create a new class from an existing class, first declare the constructor of the new class through a function, and then call the extension method shared by the new class properties. These shared properties are usually methods, but if you want to share data between instances, you should also declare it.
JavaScript does not provide an automatic mechanism for calling the parent class constructor, so the parent class must be explicitly called in the constructor through the property superclass. * parameters are always this to ensure that the constructor works in the scope of the calling function.
Listing 1. The basic method of extending the Ext component MyNewClass=function (arg1,arg2,etc) {/ / explicitly calls the parent class's constructor MyNewClass.superclass.constructor.call (this,arg1,arg2,etc);}; Ext.extend (MyNewClass,SomeBaseClass, {myNewFn1:function () {/ / etc.}, myNewFn2:function () {/ / etc.}})
When using, we need to instantiate the object:
Listing 2. Instantiate the new component object varmyObject=newMyNewClass (arg1,arg2,etc)
Once we have mastered the basic methods of extending Ext components, we are free to construct components that meet specific needs. However, the existing components and examples in Ext are always our inexhaustible source of creation. Based on three Ext components, this paper "grafts" the functions of other components, forms three new components, and realizes the functions that the existing Ext components do not have. The purpose of this article is to throw a brick to attract jade, hoping to give beginners Ext colleagues some inspiration and reference, and develop more powerful components.
Transfer the flower of Property Grid to the wood of EditorGrid
First of all, let's introduce our scenarios and actual requirements. A university should build a management system of faculty and staff scientific research funds. the system can be used for fund setup personnel to set up fund application conditions, issuance steps, etc., and applicants to fill in applicant information, apply for funds, and so on. Here is an example of building a component of a fund application condition. When formulating application conditions, condition makers can add or delete application conditions at will; for some application conditions, such as colleges, departments, gender, etc., the system can provide predefined options for condition makers to choose, while for cases such as expertise, age, or too many options can not be enumerated, directly provide an input box for condition makers to enter.
In order to build such a component with Ext, the first thing that comes to mind is to choose the EditorGrid component or the Property Grid component. EditorGrid (editable table control) extends from GridPanel to provide cell editing for selected columns. Editable columns are achieved by adding editor to the class Ext.grid.ColumnModel that represents the column information of the table. But this editor is valid for the entire column, which means that the editor for each row of data in that column is the same.
Property Grid (property sheet) extends from EditorGridPanel, so you can directly edit the contents of the attribute values section on the right. However, it is only on the right, and even if you click the cell on the left, the editor will only appear on the right. In fact, we can describe Property Grid as a hash table, with key on the left and value on the right. The key is specified by us, and users only need to modify the corresponding value.
Property Grid default editors include TextField, DateField, NumberField, and ComboBox, which can only handle general situations such as numeric, string input and date selection, Boolean selection, and so on. When we want to configure the editor in more detail, we need to use Property Grid's customEditors to set the corresponding editor for the row of data that specifies id. The settings of customEditors and source are basically the same, except that you need to correspond their property names and specify an editor for all properties in the customEditors.
Although Property Grid can customize different editors for different cells, on the one hand, this kind of table only has two columns, * columns are not editable, and the content of the table (source) needs to be determined in advance; on the other hand, when defining customEditors, you must know the content of the table (source), and you must correspond to the attribute names of the two. EditorGrid actually meets most of our needs, but we can't customize the editor for each cell, we can only specify a column editor.
After the above analysis, simply using any control, it is difficult to achieve our goal. At the same time, we find that the main problem lies in EditorGrid's column mode (ColumnModel). Property Grid extends from EditorGrid and supports cell editors by extending its ColumnModel. So we try to extend the ColumnModel of EditorGrid to make the new ColumnModel support customEditors, so that we have full control over the editor and can dynamically change the editor of the cell according to the contents of the table. Listing 3 is part of the code for the new class MyColumnModel that we extended to meet the above requirements, and listing 4 uses MyColumnModel to construct an EditorGrid as a fund application condition component.
Listing 3. Define a new class MyColumnModel Ext.ns ('Ext.ux.grid'); / / the constructor of the new class MyColumnModel, Ext.ux.grid.MyColumnModel=function (grid,store,column) {this.grid=grid; this.store=store; vargender= [[' 0100 'female']]; vardepartment= [['0200' Department of Arts'], / / omits part of the code ['0207' 'Department of Medicine]] Vartitle= [['0300' assistant'], / / omit part of the code ['0303' 'professor']]; vargenderCombo=newExt.form.ComboBox ({store:newExt.data.SimpleStore ({fields: ['value','text'], data:gender}), emptyText:', please enter', mode:'local', triggerAction:'all', valueField:'value', displayField:'text', readOnly:true}) VardepartmentCombo=newExt.form.ComboBox ({store:newExt.data.SimpleStore ({fields: ['value','text'], data:department}), / / similar to the genderCombo defined above, so some of the code is omitted. }); vartitleCombo=newExt.form.ComboBox ({store:newExt.data.SimpleStore ({fields: ['value','text'], data:title}), / / similar to the genderCombo defined above, so some of the code is omitted. }); / / when selecting "gender", "Department" and "title", the corresponding drop-down list is provided as the cell editor for users to choose from. When selecting "age" and "number of papers", a digital text box is provided for users to enter this.customEditors= {'GENDER':newExt.grid.GridEditor (genderCombo),' DEPARTMENT':newExt.grid.GridEditor (departmentCombo), 'TITLE':newExt.grid.GridEditor (titleCombo),' AGE':newExt.grid.GridEditor ({selectOnFocus:true, style:'text-align:left) ), 'PAPER':newExt.grid.GridEditor (newExt.form.NumberField ({selectOnFocus:true, style:'text-align:left;'}))}; Ext.ux.grid.MyColumnModel.superclass.constructor.call (this,column);} Ext.extend (Ext.ux.grid.MyColumnModel,Ext.grid.ColumnModel, {/ / overrides the method getCellEditor in the parent class to return different editors getCellEditor:function (colIndex,rowIndex) {varp=this.store.getAt (rowIndex); n=p.data.attrName for the cell where the value of the expression is based on the different values of the conditional column in the expression. / / the value of the conditional column of the corresponding expression if (colIndex==4) / / the column of the expression where the value propertyValue is {if (this.customEditors [n]) {returnthis.customEditors [n];} else {/ / if no specific cell editor is defined, return the normal text box editor vared=newExt.grid.GridEditor (newExt.form.TextField ({selectOnFocus:true})); returned;}} else textnthis.config.editor ); listing 4. Fund application condition component Ext.onReady (function () {varcomboData1= [['AGE',' age'], / / omit part of the code ['DEPARTMENT',' department']]; varcomboData2= [['>', 'greater than'], / / omit part of the code ['! =', 'not equal to']] Varcombo1=newExt.form.ComboBox ({id:'attrCombo', store:newExt.data.SimpleStore ({fields: ['value','text'], data:comboData1}), select', mode:'local', triggerAction:'all', valueField:'value', displayField:'text', readOnly:true} for emptyText:') Varcombo2=newExt.form.ComboBox ({id:'operatorCombo', store:newExt.data.SimpleStore ({fields: ['value','text'], data:comboData2}), / / similar to the combo1 defined above, so some of the code is omitted. }); varconditiondata= []; vargStore=newExt.data.SimpleStore ({fields: [{name:'fundConditionId'}, {name:'attrName'}, {name:'operator'}, {name:'propertyValue'}], data:conditiondata}); varsm=newExt.grid.CheckboxSelectionModel ({handleMouseDown:Ext.emptyFn}) The varcolumn= [sm, {header:' conditional id', dataIndex:'fundConditionId', hidden:true}, {header:' attribute name', dataIndex:'attrName', editor:newExt.grid.GridEditor (combo1), / / attributeRenderer method is the function used to format the output, which is omitted here. Renderer:attributeRenderer.createDelegate (this, ["properties"], 0)}, {header:' operator', dataIndex:'operator', editor:newExt.grid.GridEditor (combo2), renderer:attributeRenderer.createDelegate (this, ["operators"], 0)}, {header:' attribute value', dataIndex:'propertyValue', editor:newExt.grid.GridEditor (newExt.form.TextField ({selectOnFocus:true})), renderer:attributeRenderer.createDelegate (this, ["values"], 0)}] VarfundConditionGrid=newExt.grid.EditorGridPanel ({name:'fundCondition', id:'fundCondition', store:gStore, cm:newExt.ux.grid.MyColumnModel (this,gStore,column), sm:sm, tbar:newExt.Toolbar (['-', {text:' add condition', / / _ onAddCondition method is the response function of the button "add condition" to add a condition to the list. The handler:_onAddCondition.createDelegate (this)},'-', {text:' delete condition', / / _ onRemoveCondition method is the response function of the button "delete condition", which implements the function of deleting a condition from the list. Handler:_onRemoveCondition.createDelegate (this)},'-']), frame:true, collapsible:true, animCollapse:false, title:' Research Fund Application conditions', width:350, height:300, iconCls:'icon-grid', clicksToEdit:1, renderTo:'example1'});})
When the attribute name selects gender, professional title or department, the attribute value corresponds to different drop-down lists for the user to choose, and when the attribute name selects the age or the number of papers, the attribute value corresponds to the digital text box for the user to enter. As shown in figure 1-figure 5.
Figure 1. Application conditions for Editors' Research Assistance Fund 1
Figure 2. Application conditions for Editors' Research Assistance Fund 2
Figure 3. Application conditions for Editors' Research Assistance Fund 3
Figure 4. Application conditions for Editors' Research Assistance Fund 4
Figure 5. Application conditions for editors' research aid fund 5
This means that female teachers of the computer school who are no more than 35 years old and have the title of lecturer or above, if they have published more than 10 papers, are eligible to apply for the research fund. It can be seen that the fund reflects the scientific research support for outstanding young female teachers. Refer to the Example1.js in the sample code for the code in this section.
Using ComboBox to insert text at the cursor
In the above-mentioned faculty scientific research fund management system, if there are a large number of faculty and staff who meet the application conditions of the fund, we need to grade the applicants according to a certain scoring mechanism, and then choose the best according to the score from high to low. Here is an example of building a component that formulates a formula for calculating an applicant's score. When formulating the calculation formula, we can refer to the application conditions already defined in the above system as scoring elements, and then use operators such as addition, subtraction, multiplication and division to connect the scoring elements and proportional coefficients to form a scoring formula.
In order to achieve the above function, we consider putting a button on the right side of the text box, click the button, list all the scoring elements, select a scoring element, and insert the scoring element at the cursor position in the text box. List all the scoring elements and choose one. The implementation of * * is ComboBox, but with ComboBox, the selected value will cover all the text in the text box and cannot insert text at the cursor.
So we decided to extend ComboBox so that the new ComboBox supports inserting text at the cursor. Listing 5 is part of the code for the new class valueCombo that we extended to meet the above requirements, and listing 6 uses valueCombo as the component of the applicant's score calculation formula. The effect is shown in figures 6 and 7.
Figure 6. Insert scoring element editing scoring calculation formula
Figure 7. Score calculation formula
Listing 5. Define a new class valueCombo Ext.ns ('Ext.ux.form'); ExtExt.ux.form.valueCombo=Ext.extend (Ext.form.ComboBox, {initComponent:function () {Ext.ux.form.valueCombo.superclass.initComponent.call (this);}, setValue:function (v) {vvartext=v) / / directly display the value of the option without formatting conversion, overriding the original ComboBox formatted display / * if (this.valueField) {varr=this.findRecord (this.valueField,v); if (r) {text=r.data [this.valueField];} elseif (Ext.isDefined (this.valueNotFoundText)) {text=this.valueNotFoundText;} * / this.lastSelectionText=text; if (this.hiddenField) {this.hiddenField.value=v } Ext.ux.form.ComboBox.superclass.setValue.call (this,text); this.value=v; returnthis;}, / / private onSelect:function (record,index) {if (this.fireEvent ('beforeselect',this,record,index)! = = false) {varstr=record.data [this.valueField | | this.displayField]; / / to insert text at the cursor vartc=this.getRawValue (); vartclen=this.getRawValue (). Length; this.focus () / / the following code only takes effect on Firefox: if (typeofdocument.selectionstarting = "undefined") {document.selection.createRange (). Text=str;} else {this.setValue (tc.substr (0menth.el.dom.selectionStart) + str + tc.substring (this.el.dom.selectionStart,tclen));} this.collapse (); this.fireEvent ('select',this,record,index);}}, onLoad:function () {if (! this.hasFocus) {return } if (this.store.getCount () > 0) {this.expand (); this.restrictHeight (); if (this.lastQuery==this.allQuery) {/ / if (this.editable) {/ / this.el.dom.select (); to maintain the cursor position, comment out this code / /} if (! this.selectByValue (this.value,true)) {this.select;}} else {this.selectNext () If (this.taTask.delay (this.typeAheadDelay);} else {this.onEmptyResults ();} / / this.el.focus ();}, initQuery:function () {/ / this.doQuery (this.getRawValue ()); listing 6. Applicant score calculation formula component varcomboData= [['AGE',' age'], / / omit part of the code ['DEPARTMENT',' faculty']] Cls: "x-textfield-button-trigger"}})
The calculation formula reflects the encouragement and support to young staff and female staff. Refer to the Example2.js in the sample code for the code in this section.
Implement TwinTriggerField with ComboBox
In the above-mentioned teaching staff scientific research fund management system, we need a control to query the details of the staff. As long as you enter the employee number or select an employee number from the drop-down list, you can automatically load all the information for that employee. At the same time, I hope to be able to query qualified employees according to the search criteria, select an employee from them, and view his details.
According to this requirement, we need to build a component to query employees. When we enter the first few digits of the employee number in the text box, we can automatically list all relevant employee numbers, or select an employee number directly from the drop-down box, and then automatically load the employee information. When you click the search button on the right side of the text box, a new window opens, in which you can search according to the employee's position, department, date of birth, etc., and automatically load the employee's information after selecting the employee. If you can combine the functions of ComboBox and TwinTriggerField, it will be the most direct and convenient way to achieve this requirement.
Listing 7 is part of the code for the new class ComboSearchField that we extended to meet the above requirements, and listing 8 uses ComboSearchField to construct a Form as a faculty information query control. Please refer to Example3.js for the complete code in this section. The effect is shown in figures 8 and 9.
Figure 8. TwinTrigger drop-down list
Figure 9. Load employee information
Listing 7. Define a new class ComboSearchField Ext.ns ('Ext.ux.form'); ExtExt.ux.form.ComboSearchField=Ext.extend (Ext.form.ComboBox, {initComponent:function () {Ext.ux.form.ComboSearchField.superclass.initComponent.call (this)) This.triggerConfig= {/ / use TwinTrigger style tag:'span',cls:'x-form-twin-triggers',cn: [{tag: "img", src:Ext.BLANK_IMAGE_URL,cls: "x-form-trigger" + this.triggerClass}, / / use default ComboBox style {tag: "img", src:Ext.BLANK_IMAGE_URL,cls: "x-form-trigger" + this.trigger2Class} / / Custom Trigger2 style]} }, getTrigger:function (index) {returnthis.triggers [index];}, initTrigger:function () {varts=this.trigger.select ('.x-form-trigger',true); this.wrap.setStyle ('overflow','hidden'); vartriggerField=this; ts.each (function) {t.hide=function () {varw=triggerField.wrap.getWidth (); this.dom.style.display='none'; triggerField.el.setWidth (w-triggerField.trigger.getWidth ());} T.show=function () {varw=triggerField.wrap.getWidth (); this.dom.style.display=''; triggerField.el.setWidth (w-triggerField.trigger.getWidth ());}; vartriggerIndex='Trigger'+ (index+1); if (this ['hide'+triggerIndex]) {t.dom.style.displayfully distributed noneyed;} / / this.mon (t on'+triggerIndex+'Click' clickbacks). This, {preventDefault:true}) / define * * trigger trigger events if (index==0) t.on ("click", this ['onTriggerClick'], this, {preventDefault:true}); / / define trigger events if (index==1) t.on ("click", this [' onTrigger2Click'], this, {preventDefault:true}) of the second trigger; t.addClassOnOver ('Xmurf'); t.addClassOnClick ('xMurfeller');}, this) This.triggers=ts.elements;}, validationEvent:false, validateOnBlur:false, trigger2Class:'x-form-search-trigger', width:180, hasSearch:false, paramName:'query', onTrigger2Click:Ext.emptyFn}); listing 8. Staff information query control Ext.onReady (function () {varemployeeData= [['20001234'], / / omit part of the code [' 20091546']] VarsearchField=newExt.ux.form.ComboSearchField ({id: "employeeId", fieldLabel:' employee code'+'*', store:newExt.data.SimpleStore ({fields: ['value'], data:employeeData}), valueField:'value', displayField:'value', typeAhead:false, allowBlank:false, mode:'local', triggerAction:'all', / / Open customer query window Code from onTrigger2Click:_searchCustomer.createDelegate (this), listeners: {/ / load customer information according to selected customer code, code from select:_select_customer_id.createDelegate (this)}}) / / the following code only runs valid / / initialize the generated form varemployeeForm=newExt.FormPanel ({id: "employeeForm", frame:true, title: "staff Information query", autoScroll:true, items: [{layout:'column', border:false, autoHeight:true, defaults: {layout:'form', border:false, width:100, bodyStyle:'padding:4px'}, items: [{columnWidth:0.33] Name: "form1", id: "form1", defaultType:'textfield', defaults: {width:200}, items: [searchField, {fieldLabel:' title', name:'title', id:'title', disabled:true}, {fieldLabel:' birth date', name:'birthday', id:'birthday', disabled:true}, {fieldLabel:' contact number', name:'tel', id:'tel' Disabled:true}]}, {columnWidth:0.33, / / omitted}, {columnWidth:0.33, / / omitted}]], renderTo:'example3'}) })
After introducing the basic concept of Ext and the general method of extending Ext, taking three application scenarios as examples, this paper describes in detail how to develop a new control that meets the actual needs from the existing Ext controls and draws lessons from the functions of other controls. For beginners, this "flower-to-wood" development method can not only enable developers to have an in-depth understanding of the implementation behind each control, but also quickly help them achieve new functions and new requirements. It can be said that it is a recommended way of innovation.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.