原文链接: HTML and ExtJS Component http://skirtlesden.com/articles/html-and-extjs-components
文章详细阐述了如下关键概念: ExtJS中的Component和HTML的Element的联系,关联,区别 autoEl childEls targetEl tpl & data renderTpl & renderData baseCls 等等.
HTML and ExtJS Components
If you have a background in creating websites with raw HTML then it's only a matter of time before you'll find yourself drowning in ExtJS components, knowing exactly what HTML you'd like to use but having absolutely no idea how to get ExtJS to create it. In this article we'll cover the main techniques at your disposal and attempt to answer the question: “How do I create some simple HTML with an ExtJS component?”.
Introduction
First let's tackle some common misconceptions.
- If you've spent a lot of time working with other frameworks then you might fall into the trap of viewing an ExtJS component as little more than an abstraction for manipulating a DOM element. In other words, the DOM is king.
- On the flip side, once you get a taste for components, it's easy to lose sight of the DOM altogether. You start seeing every rectangle in your UI as just another component and the DOM is irrelevant.
Interestingly, both extremes lead to similar mistakes, with simple tasks approached heavy-handedly and lots of components used to do a job where a single component would suffice. As you might expect, the reality lies somewhere between these two extremes. The DOM certainly isn't irrelevant but it's the components that are king.
First and foremost, a component is a JavaScript object. This object has many responsibilities, the most important of which is to create and manage DOM elements. Each component creates a single outermost element, known as el, and then adds any other elements it needs inside that el.
The parent-child relationship formed by a container and its items is reflected in their DOM elements. The main el for a component is always a descendant of the el for its parent container.
The initial creation of DOM elements by a component is a process known as rendering. The rendering process only happens once per component and is highly optimized to ensure that the rendering of a large component tree is as fast as possible.
It's not uncommon for a component to need to adjust its elements at some subsequent point, usually in response to user interaction. Often this is something as simple as adding a CSS class but a component can completely change its DOM structure if required. In general the only restriction is that the outer el must remain the same element, though some component types may impose much tighter restrictions.
The terms rendering and layout should not be confused. Layout is the process of positioning and sizing components and their elements. Unlike rendering, layout is not a one-off process and it is often necessary to re-run layouts when a component makes changes to its DOM elements.
Rendering a Component
Let's start with a really simple example to see what gets rendered by default.
// The renderTo config option specifies a parent DOM element for rendering the component.
// For brevity it is not shown in the remaining examples.
new Ext.Component({
renderTo: 'component-demo'
});
The problem with this example is that it's so simple we can't actually see it.
However, it does have a presence in the DOM.
<div id="component-1001" class="x-component x-component-default" role="presentation"></div>
Let's break that down.
- A component renders as a single
<div>
. More sophisticated components may have multiple elements but there will always be a single, outermost element that acts as the primary element for the component. After a component is rendered you can access this element via the el property of the component. - The id attribute of the element matches the id of the component.
- There are two CSS classes. These classes are derived from the baseCls and ui config options. These are advanced settings and are rarely used in client code. We will see an example of using baseCls later.
- Depending on your ExtJS version you may see other attributes, such as an ARIA role.
When we discard the fluff we're left with something very simple:
<div id="component-1001" ...></div>
Let's add a few more options and some CSS so that we can actually see the component.
new Ext.Component({
cls: 'green-box',
height: 60,
width: 300
});
.green-box {
background-color: #fec;
border: 2px solid #5a7;
border-radius: 5px;
box-shadow: 2px 2px 2px #bbb;
padding: 5px;
}
The three settings we've added translate pretty directly into the markup for our component's element:
<div id="component-1001" class="green-box ..." style="height: 60px; width: 300px;" ...></div>
Using this as the basis for the examples that follow we can now start to add to our HTML.
The html Config Option
Dirty and direct, the html config option specifies a string of HTML content to be injected directly into the component.
new Ext.Component({
html: 'Some <b>HTML</b> content',
...
});
<div id="..." class="green-box x-component x-component-default" ...>
Some <b>HTML</b> content
</div>
For simple, static HTML the html config option does the job fine. The content can also be updated by passing a string of HTML to the update method.
var summary = new Ext.Component({
html: 'Some <b>content</b>',
...
});
new Ext.button.Button({
...
handler: function() {
summary.update('Some slightly different <b>content</b>');
}
});
However, the html config option only affects the component's content. If we want to customize the outer el itself then we'll need to use a different approach.
autoEl
To change the element name of the outer el we can use the autoEl config option:
new Ext.Component({
autoEl: 'form',
...
});
It looks just the same as before but the markup has changed:
<form id="..." class="green-box x-component x-component-default" ...></form>
The autoEl can also be used to change other aspects of a component's el by passing a config object rather than a string. For example, we can add other attributes or simple HTML content:
new Ext.Component({
autoEl: {
href: 'javascript:alert(%22Clicked!%22)',
html: 'Click Me!',
tag: 'a'
}
});
<a href="javascript:alert(%22Clicked!%22)" ...>Click Me!</a>
The autoEl config option is used as a DomHelper config so it accepts all the same options. e.g. Creating child elements via cn:
new Ext.Component({
...
autoEl: {
cn: [
'Some ',
{tag: 'b', cn: 'HTML'},
' content'
]
}
});
<div ...>
Some <b>HTML</b> content
</div>
autoEl is fine as far as it goes but it has two key problems: it's difficult to parameterize and it isn't very human-readable once you start adding child elements. For richer content it's much easier to use templates.
tpl & data
The config options tpl and data work in tandem. tpl specifies a template (using XTemplate syntax) and the data is then applied to that template. It's common for the tpl to be specified at the class level and the data to vary between instances. However, in these simple examples we'll show them both specified at the instance level:
new Ext.Component({
...
tpl: '{name} is {age} years old and lives in {location}',
data: {
age: 26,
location: 'Italy',
name: 'Mario'
}
});
<div ...>
Mario is 26 years old and lives in Italy
</div>
Much like with the html config option, the content can be updated using the update method. Instead of passing a string we pass a new data object, which is then applied to our template to generate the new content.
var summary = new Ext.Component({
...
tpl: '{name} is {age} years old and lives in {location}',
data: {
age: 26,
location: 'Italy',
name: 'Mario'
}
});
new Ext.button.Button({
...
handler: function() {
summary.update({
age: 7,
location: 'Japan',
name: 'Aimee'
});
}
});
XTemplates have a rich and powerful syntax that goes well beyond substituting data values. A full discussion of templates is beyond the scope of this article but the next example gives a sense of what's possible. It shows how to generate an HTML list using an array of values.
new Ext.Component({
...
data: ['London', 'Paris', 'Moscow', 'New York', 'Tokyo'],
tpl: [
'<ul>',
'<tpl for=".">',
'<li>{.}</li>',
'</tpl>',
'</ul>'
]
});
- London
- Paris
- Moscow
- New York
- Tokyo
The HTML generated for this component is:
<div ...>
<ul>
<li>London</li>
<li>Paris</li>
<li>Moscow</li>
<li>New York</li>
<li>Tokyo</li>
</ul>
</div>
Note that the <ul>
is still wrapped in the component's main el. If we wanted to remove that <div>
we could use theautoEl config described earlier to switch the el to a <ul>
and remove the <ul>
from the template.
new Ext.Component({
...
autoEl: 'ul',
data: ['London', 'Paris', 'Moscow', 'New York', 'Tokyo'],
tpl: [
'<tpl for=".">',
'<li>{.}</li>',
'</tpl>'
]
});
- London
- Paris
- Moscow
- New York
- Tokyo
HTML Encoding
XTemplates do not HTML encode values by default. However, it's easy to pass values throughExt.util.Format.htmlEncode from within a template:
new Ext.Component({
...
tpl: '<b>Email:</b> {email:htmlEncode}',
data: {
email: 'John <john@example.com>'
}
});
Without correct encoding, the email address inside the <...>
would be lost.
targetEl
For more complex components, such as panels or windows, the HTML provided by the configuration options html and tplisn't injected directly into the el. To ensure it doesn't overwrite the header or toolbars it's written to the body element instead.
new Ext.panel.Panel({
...
bodyPadding: 10,
title: 'Title',
tpl: 'Some <b>{lang}</b> content',
data: {
lang: 'HTML'
}
});
The element used for this purpose is known as the targetEl. We'll see how to change the targetEl for a custom component later.
Note that autoEl is still responsible for configuring the outer el, it isn't affected by the targetEl.
Recap
At this stage we're ready to answer our original question: “How do I create some simple HTML with an ExtJS component?”
- Use autoEl to configure the outer element.
- Use the html config to set simple HTML content.
- Use tpl and data if you need something a little more dynamic.
However, creating the HTML is just the first part of the story. The next three sections introduce some common techniques for adding interactions to custom components.
Events
Let's add a click event to our component. The approach used here is quite naive but it is relatively easy to understand.
var clickCmp = new Ext.Component({
...
count: 0,
html: 'Click Me',
listeners: {
// Add the listener to the component's main el
el: {
click: function() {
clickCmp.count++;
clickCmp.update('Click count: ' + clickCmp.count);
}
}
}
});
The key thing to notice is that the listener is being registered on the el rather than on the component. By default a component doesn't have a click listener so we can't listen for that directly.
There are several problems with this example, the most important of which is the way the click listener obtains a reference to the component. In general it just isn't practical to capture a reference in the closure like this.
A much tidier way to do this is to add the listener in an override of initEvents. In the following example we define a custom component class that supports a handler config for reacting to clicks:
Ext.define('ClickComponent', {
extend: 'Ext.Component',
initEvents: function() {
this.callParent();
// Listen for click events on the component's el
this.el.on('click', this.onClick, this);
},
onClick: function() {
// Fire a click event on the component
this.fireEvent('click', this);
// Call the handler function if it exists
Ext.callback(this.handler, this);
}
});
We might use it something like this:
new ClickComponent({
...
count: 0,
html: 'Click Me',
handler: function() {
this.count++;
this.update('Click count: ' + this.count);
}
});
In our onClick method we also fire a click event, though we aren't using it in this example. Note that this is an event fired on the component, in reaction to the event fired by the element. It's important to understand the difference between these two events.
Event Delegation
With a bit of event delegation and some CSS we can quickly add a bit of interactivity to the list example we saw earlier. This example is a lot more advanced so we'll need to dissect it a little.
new Ext.Component({
...
autoEl: 'ul',
data: ['London', 'Paris', 'Moscow', 'New York', 'Tokyo'],
listeners: {
// Add the listener to the component's main el
el: {
// Use a CSS class to filter the propagated clicks
delegate: '.list-row',
click: function(ev, li) {
// Toggle a CSS class on the li when it is clicked
Ext.fly(li).toggleCls('list-row-selected');
}
}
},
tpl: [
'<tpl for=".">',
'<li class="list-row">{.}</li>',
'</tpl>'
]
});
.list-row {
border: 1px solid #f90;
border-radius: 5px;
cursor: pointer;
list-style: none outside;
padding: 5px;
}
.list-row-selected {
background-color: #f90;
}
- London
- Paris
- Moscow
- New York
- Tokyo
The markup looks like this:
<ul id="..." ...>
<li class="list-row">London</li>
<li class="list-row">Paris</li>
<li class="list-row">Moscow</li>
<li class="list-row">New York</li>
<li class="list-row">Tokyo</li>
</ul>
When an <li>
is clicked, the CSS class list-row-selected is added to it.
If you haven't used event delegation before then this example may be a bit overwhelming. We're adding a single clicklistener to the component's el, which is a <ul>
in this example. However, we aren't interested in clicks on the <ul>
itself, we're using event propagation to respond to clicks on the child <li>
elements. We target these elements using the delegate config option. Theoretically we could just use the tag name as the delegate selector but in practice it's much more common to use a CSS class. Our <li>
elements each have the class list-row so we can use that.
The setting delegate: '.list-row'
has two effects:
- Clicks that aren't on an
<li class="list-row">
element, or one of its descendants, will be ignored. - The second argument passed to the listener function will be the
<li>
element. Even if our<li>
had contained child elements, the element passed to the listener would still be the enclosing<li>
.
This component could be refactored into a class using initEvents just like the previous example.
DataView
If we wanted to push this list example further we might switch to using a DataView instead. The class Ext.view.View, usually referred to as DataView, provides automatic binding to a store with functionality like selection built in.
A full explanation of DataViews is beyond the scope of this article but the following example shows how we might use aDataView to improve upon our list implementation.
new Ext.view.View({
...
autoEl: 'ul',
itemSelector: '.list-row',
overItemCls: 'list-row-over',
selectedItemCls: 'list-row-selected',
simpleSelect: true,
// An ExtJS store or store config
store: {
data: [{city: 'London'}, ...],
fields: ['city']
},
tpl: [
'<tpl for=".">',
'<li class="list-row">{city}</li>',
'</tpl>'
]
});
- London
- Paris
- Moscow
- New York
- Tokyo
The most important setting here is itemSelector. It has a role very similar to the delegate option we saw earlier. It allows the DataView to map the DOM elements back to their records in the store, so that clicking selects the correct record.
The remaining sections of this article introduce some advanced techniques for rendering components. The major benefit of understanding this material is that it will help you to read the ExtJS source code. It's rare that you would need to write something like this yourself.
These techniques complement each other and aren't easily demonstrated in isolation. A combined example is included at the end.
renderTpl and renderData
The config options renderTpl and renderData are similar to tpl and dataexcept they are run just once, during the initial rendering of the component. While both templates are responsible for creating the component's inner markup, the elements created by the renderTpl can be thought of as being part of the component's own markup, rather than being part of its content.
For example, earlier we saw a tpl used with a panel. While the tpl was responsible for rendering the dynamic content of the panel, the Panel class also has a renderTpl. This renderTpl creates the scaffolding elements of the panel that hold the header, toolbars and body.
Whereas a tpl might be specified on either the class or an instance, the renderTpl is almost exclusively set on the class definition.
baseCls
The baseCls is at the heart of the styling for a component. It is not only added to the outer el but it is also used as a prefix for CSS classes added to the main child elements of a component. The creation of these elements and their CSS classes is usually performed in the renderTpl.
Several ExtJS components set their own baseCls. For example, button uses x-btn, panel uses x-panel and window usesx-window. While it is frequently used internally by the library, it is rarely appropriate to use it in application code. You should only set the baseCls if you want to build your component's CSS from scratch. For example, you might change thebaseCls of a button if you want to completely remove the default styling.
Setting a baseCls requires extreme caution. A component may be relying on some CSS properties having particular values and changing them may prove troublesome, especially when you try to upgrade to a newer version of ExtJS. If you're just looking to make a small CSS change then consider using one of the myriad of other techniques that are available.
childEls
ExtJS components store direct references to some of their elements. This is usually so that they can be modified without having to find the relevant child element each time. Once rendered, all components have a property called el that holds their outermost element. The config option childEls is used to create similar references to other elements.
For example, a panel has two such properties, el and body. A button has several, including btnIconEl and btnInnerEl, which are used to update the button's icon and text respectively.
A consequence of storing these references is that these components cannot make arbitrary changes to their markup. The elements that are referenced cannot be removed when changes are made. As a result, it doesn't make sense forchildEls to reference elements created by a tpl, they are almost always created by the renderTpl.
Within the renderTpl, the convention is to give each element an id which appends the name of its corresponding property to the id of the component. This allows the property to be created using a quick lookup immediately after rendering.
Putting It All Together
The following example is quite involved and combines several of the ideas we've seen previously to form a much more complete and sophisticated component. What we're looking to create is this:
Biography
We split the class definition into two parts. First, we create a fairly generic component that has a header and body region with the appropriate styling. Nothing in this class is specific to displaying the biography data.
// Note: This is correct for ExtJS 4.1 and 4.2. This page
// uses 4.0 so requires a slightly modified version.
Ext.define('TitledComponent', {
extend: 'Ext.Component',
baseCls: 'titled-component',
childEls: ['body', 'headerEl'],
renderTpl: [
'<h4 id="{id}-headerEl" class="{baseCls}-header">{header:htmlEncode}</h4>',
'<div id="{id}-body" class="{baseCls}-body">{% this.renderContent(out, values) %}</div>'
],
getTargetEl: function() {
return this.body;
},
// Override the default implementation to add in the header text
initRenderData: function() {
var data = this.callParent();
// Add the header property to the renderData
data.header = this.header;
return data;
},
setHeader: function(header) {
this.header = header;
// The headerEl will only exist after rendering
if (this.headerEl) {
this.headerEl.update(Ext.util.Format.htmlEncode(header));
}
}
});
Next we define a subclass that is specifically tailored to displaying biographies:
Ext.define('BiographyComponent', {
extend: 'TitledComponent',
xtype: 'biography',
header: 'Biography',
tpl: '{name} is {age:plural("year")} old and lives in {location}',
// Override update to automatically set the date in the header
update: function(data) {
this.callParent(arguments);
this.setHeader('Biography updated at ' + ...);
}
});
Then we create an instance, which only needs the data:
var summary = new BiographyComponent({
data: {
age: 26,
location: 'Italy',
name: 'Mario'
}
});
Add a button to update the biography:
new Ext.button.Button({
...
handler: function() {
// Update the body content via the tpl
summary.update({
age: ...,
location: ...,
name: ...
});
}
});
The generated HTML is really quite simple:
<div id="biography-1035" class="titled-component ..." ...>
<h4 id="biography-1035-headerEl" class="titled-component-header">Biography</h4>
<div id="biography-1035-body" class="titled-component-body">Mario is ...</div>
</div>
The CSS isn't very interesting but here it is anyway. The only thing worth noting is how the selectors are tied to thebaseCls we specified on TitledComponent. There's nothing specific to BiographyComponent.
.titled-component {
background-color: #fec;
border: 2px solid #5a7;
border-radius: 5px;
box-shadow: 2px 2px 2px #bbb;
display: inline-block;
}
.titled-component-body {
margin: 10px;
}
.titled-component-header {
background-color: #5a7;
color: #fff;
font-weight: 700;
margin: 0;
padding: 5px 10px;
text-align: center;
}
We've already met most of it but let's blitz through those class definitions and see what's going on.
-
xtype: 'biography'
. The xtype is automatically included as a prefix for the id of our component instance, which isbiography-1035
in this example. This same id is used as the id for the outer el and we also use it twice in the renderTpl. -
baseCls: 'titled-component'
. This CSS class is added to the outer el. Also notice how it is used as a prefix for the CSS classes of the inner elements. -
childEls: ['body', 'headerEl']
. Properties referencing these two childEls are created immediately after rendering. The DOM elements are found using their ids. The body element is used in the method getTargetEl, whereas the headerEl can be seen in the method setHeader. - The values for the renderTpl come from initRenderData. The id and baseCls are included by default and we also add our header property.
- Within the renderTpl is the magical incantation
'{% this.renderContent(out, values) %}'
. This needs to appear within the targetEl and is used to inject the component's content. In ExtJS 4.0 the targetEl would have been left empty in the template and the content would have been injected after the targetEl had been added to the DOM. That proved too slow so from ExtJS 4.1 onwards the content has been rendered directly by the template. If you wanted to extend a container it would be'{% this.renderContainer(out, values) %}'
instead. - getTargetEl returns the body element created by the childEls config. This is required so that the updatemethod of the component updates the correct element. This should not be confused with the update method that is called in setHeader, which is a method of the headerEl element, not the component.
- setHeader updates the contents of the header. It is written in such a way that it could be called before or after the component is rendered.
Even if you never have to write a low-level component like this, understanding the techniques it uses should help you to get a better grasp on the ExtJS source code. The TitledComponent class uses patterns that are typical of the standard ExtJS components. The BiographyComponent class, in contrast, is much more typical of an application class.
相关推荐
### ExtJs组件类的对应表解析 #### 引言 ExtJs是一款强大的JavaScript框架,用于构建复杂的、数据密集型的应用程序。它提供了大量的组件和工具,使得开发者能够快速地创建美观且功能丰富的用户界面。本文将详细...
通过研究和理解"ExtJS日期多选组件源码",开发者可以深入学习ExtJS组件设计、事件处理、数据绑定等核心概念,并能进一步定制适合自己项目需求的日期选择组件。这样的组件对于提高开发效率和用户体验具有积极的意义。
- 对于ExtJS,Spket可以识别和理解ExtJS组件和API,提供实时的代码提示,帮助开发者快速编写代码。 - 还包括模板、调试工具和集成版本控制系统等其他特性,为ExtJS开发提供了一个全面的工作环境。 3. **Ext包管理...
EXTJS 提供了简单易用的API来创建和管理右键菜单,可以轻松地将其与任何组件关联,如表格、树形视图等。这为用户提供了更直观的交互方式,提升了应用的易用性。 在EXTJS 3.0 中,网格(Grid)组件也是不可或缺的一...
8. **集成其他EXTJS组件**:学习如何将图表与其他EXTJS组件(如表格、面板)一起使用,构建完整的应用界面。 通过深入学习并实践EXTJS的图形编程,开发者能够构建出具有专业级图形展示能力的Web应用,为用户提供...
开发插件的基本步骤包括定义插件类、实现插件功能和将插件与组件关联。 1. **定义插件类**: 在ExtJS中,插件通常是一个实现了`Ext.AbstractPlugin`接口的类。你需要定义一个类,并在类中声明`ptype`属性,以便于...
例如,可以在树组件中选择一项,然后在关联的网格中显示其详细信息;或者通过表单收集用户输入,再用查询功能对数据进行筛选。在项目“bookSys”中,可能就是构建一个图书管理系统,用户可以通过树形结构浏览书籍...
数据绑定是ExtJS的一个强大特性,它允许组件与数据模型直接关联,当模型数据发生变化时,界面会自动更新,反之亦然。这种实时的数据同步大大简化了数据操作。 9. **AJAX支持** ExtJS内置了强大的AJAX功能,可以...
它通常与一个隐藏的`<input type="file">`元素关联,允许用户在表单中选择文件。为了实现实际的文件上传,我们需要配置这个组件的`url`属性,指向服务器端接收文件的接口。 描述中提到的`upload.js`可能是一个...
手册应该会包含如何创建和配置数据存储,以及如何将存储与网格等组件关联起来的说明。 除此之外,ExtJs2.0中文手册还会介绍一些高级特性,例如布局管理器,它允许开发者以声明性的方式控制组件的大小和位置。布局...
- `resources` 文件夹:存储CSS样式、图片和其他资源文件,用于自定义EXTJS组件的外观。 - `docs` 文件夹:可能包含了EXTJS的API文档,供开发者参考。 - `build` 文件夹:可能包含编译后的版本,适合生产环境使用。 ...
在ExtJS框架中,3.4.0版本提供了丰富的组件和功能,适合构建复杂的Web应用程序。以下是对标题和描述中提及的几个关键知识点的详细解释: 1. **Ext JS 下载及配置** 在开始使用Ext JS前,你需要从官方网站下载相应...
3. **数据绑定**:ExtJS支持数据绑定,允许将数据模型与UI组件直接关联,实现数据的实时更新。这对于创建动态和响应式的应用至关重要。 4. **Store与Model**:Store是数据存储的容器,它可以加载远程数据,如JSON或...
5. 绑定数据:创建Store,加载数据,并与组件关联。 6. 处理事件:监听组件的事件,编写相应的处理函数。 五、优化与进阶: 1. 模块化:使用ExtJS的“类”系统,将代码拆分为小模块,提高代码复用性和可维护性。 2....
ExtJS 4.0提供了一套丰富的组件库,包括表格、面板、表单、树形结构等,所有组件都可以动态创建和修改。这使得开发者可以构建高度交互和可配置的用户界面。 4. Store管理 Store是ExtJS 4中处理数据的主要对象,它...
3. **数据绑定**:ExtJS的数据绑定功能允许开发者将UI组件与数据源进行关联,实现数据的实时更新。数据模型(Model)和数据存储(Store)是实现这一功能的关键部分。 4. **事件处理**:事件驱动编程是ExtJS的核心...
2. **数据绑定**:ExtJS引入了一种强大的数据绑定机制,使得UI组件可以直接与数据模型关联,当数据变化时,UI会自动更新,反之亦然,大大简化了数据驱动应用的开发。 3. **MVC模式**:框架支持Model-View-...
通过`LovCombo.js`中的源码,开发者可以学习到如何扩展和定制ExtJS组件,以及如何处理多选和全选功能。同时,这也展示了如何将自定义组件与CSS样式结合,以创建具有吸引力和用户体验友好的Web应用。