[url=http://hi.baidu.com/greenboy1985/blog/item/2d7d5bab5ab2b0f61e17a2be.html]ExtJS中的renderTo和applyTo的差别[/url]
[url=http://yahaitt.javaeye.com/blog/249444]对applyTo和renderTo的理解和思考[/url]
个人认为这两篇文章写的不够通俗。写一个简单的例子来看看最终生成了什么代码,
[url=ext-3.1.0/resources/css/ext-all.css]<script type="text/javascript" src="ext-3.1.0/adapter/ext/ext-base-debug.js"></script>
<script type="text/javascript" src="ext-3.1.0/ext-all-debug.js"></script>
<script type="text/javascript" src="ext-3.1.0/src/locale/ext-lang-zh_CN.js"></script>
<script type="text/javascript">
Ext.onReady(function() {
var button = new Ext.Button({
renderTo: 'button',
text:'OK'
});
});
</script>
</head>
<body>
<div id="button">sadfa</div>
</body>
</html>
此代码生成的html如下:
[img]http://files.jb51.net/upload/2010-1/20100107211543318.png[/img]
如果是applyTo:button,则生成的代码为:
[img]http://files.jb51.net/upload/2010-1/20100107211543807.png[/img]
很明显,简单的说,[b]applyTo是将组件加在了指定元素之后,而renderTo则是加在指定元素之内[/b]。
接下来,我们再稍稍探寻下extjs源码的奥秘。看看extjs内部是如何使用这两个配置项的,利用firebug插件调试一下ext-all-debug.js这个文件。
在Ext.Component的构造函数Ext.Component = function(config){…}中有这样一段代码(3.1.0版本是9270行):
if(this.applyTo){
this.applyToMarkup(this.applyTo);
delete this.applyTo;
}else if(this.renderTo){
this.render(this.renderTo);
delete this.renderTo;
}
可见applyTo属性使得Component调用applyToMarkup方法,而renderTo使得它调用render方法,并且如果两个都设置的话仅有applyTo有效,这点在extjs的文档中也有特别指出。
appylToMarkup方法如下(3.1.0版本是9560行),
[url=http://yahaitt.javaeye.com/blog/249444]对applyTo和renderTo的理解和思考[/url] 中提到的el配置属性,我查extjs的文档发现这是一个只读属性,虽然有方法覆盖它,不过一般不需要手动设置,下面是Panel的公共属性el的文档原文:
[b][url=http://www.extjs.com/source/Component.html#prop-Ext.Component-el]el[/url][/b] : Ext.Element
The [url=http://www.extjs.com/output/Ext.Element.html]Ext.Element[/url] which encapsulates this Component. Read-only.
This will [i]usually[/i] be a <DIV> element created by the class's onRender method, but that may be overridden using the [code][url=http://www.extjs.com/output/Ext.Component.html#Ext.Component-autoEl]autoEl[/url][/code] config.
[b]Note[/b]: this element will not be available until this Component has been rendered.
所以我估计此文写的是以前版本的extjs。个人认为,el是紧包裹着extjs组件的一个DOM节点,一般是由extjs自己生成的,好像细胞膜一样,如果拨开了它,那么这个组件就不完整了,很可能会表现的不正常。而render方法中的container(也就是applyTo中指定元素的父元素,renderTo中指定的元素),是该组件的父元素,这个container中可以包括其他的html元素或者extjs组件。
综上所述,其实applyTo和renderTo没有很本质区别,只是render的位置不同。