ExtJS中的renderTo何applyTo的差別

 

appyTo

renderTo

在外部的寫法

applyToMarkup

render

  老實不客氣的說:沒有Panel,就沒有extjs的盛名。那些最常見的UI組件都是繼承自它。暴爽的東西啊。我就在想,這麼好的東西怎麼會出現得這麼晚呢?

  在這一篇中,將詳細講一講Ext.Panel的方方面面。

  現在遇到了一些問題:

  一、顯示的問題

  事實上,這個問題是所有組件的問題,凡是從Ext.Component繼承的類都面臨這個問題。

  例如,我寫了一行這樣的代碼,但是沒有任何結果:

  var panel=new Ext.Panel({width:300,height:300,title:'標題欄'});

  這是什麼原因呢?

  if(this.applyTo){
    this.applyToMarkup(this.applyTo);
    delete this.applyTo;
  }else if(this.renderTo){
    this.render(this.renderTo);
    delete this.renderTo;
  }

  這幾行代碼是寫在Ext.Component的構造函數中的。它標示如果applyTo、renderTo有值,就會在對象創建的時候直接呈現,如果這兩值都沒有,那就只能手工調用render函數了。

  然而這有一個問題,applyTo與renderTo倒底有什麼區別,它們取值類型可以是哪些呢?看代碼。

  applyTo的情況依賴於this.applyToMarkup來實現呈現。找到它的代碼:

  applyToMarkup : function(el){
   this.allowDomMove = false;
   this.el = Ext.get(el);
   this.render(this.el.dom.parentNode);
  }

  而renderTo的情況是直接依賴於this.render(this.renderTo)的。這兩者的差別很明顯了,但是,這個問題到目前還不能說清楚,我發現,Ext.Panel最後生成的代碼如下:

  <div id="panel2" class="x-panel" style="width: 300px;">
    <div id="ext-gen14" class="x-panel-header x-unselectable" style="-moz-user-select: none; cursor: move;">
      <span id="ext-gen18" class="x-panel-header-text">這是標題欄</span>
    </div>
    <div id="ext-gen15" class="x-panel-bwrap">
      <div id="ext-gen16" class="x-panel-body" style="width: 298px; height: 273px;">這是面板的內容!!!</div>
    </div>
  </div>

  由上代碼可知,panel的代碼總是外面一個容器:x-panel,然後裏面幾個,這兒是:x-panel-header、x-panel-bwrap。現在可以說一說renderTo與appplyTo的區別了。

  renderTo與applyTo的傳入參數的數據類型與Ext.get的參數類型一樣,可是dom、string、Element。它們最大的不同在於容器,這個容器不是指x-panel所對應的元素,而是指x-panel所對應元素的父元素。由源代碼可知:

  當爲applyTo時,它調用render(this.el.dom.parentNode);可見,x-panel的容器爲applyTo對應元素的父元素。也即是applyTo事實上就是x-panel。而renderTo時,renderTo所對應元素是x-panel的容器。如何驗證這個問題呢?請到FireBug中看一看就曉得了。

  上面說了一大通,我再總結一下:

  renderTo:對應x-panel所在div的父元素;

  applyTo:對應x-panel所在div本身。

  二、Ext.Component的幾個極其重要的成員

  component.el:在panel中相當於x-panel所對應的div。它表示Component所對應的最外層html元素。

  component.id:在panel中相當於x-panel所對應的div的id,如果x-panel所在div沒有id,那麼就自己分配一個。

  component.container:它在panel中相當於x-panel所在div的父元素。即x-panel的容器。也即是:component的容器。

  如果沒有分清楚這個問題,那麼下面代碼會產生問題:

  var p=new Ext.Panel({title:'my title',width:300,height:300,renderTo:'panel1'});

  console.info(Ext.getCmp('panel1'));

  結果如何呢?undefined!!

  爲什麼是這樣呢,因爲,getCmp用的id即是component.id。而這個id對應的是x-panel所在元素的id或者自由分配的。而renderTo對應的元素不是x-panel。而是x-panel的父親。這個問題極容易搞錯。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章