簡體   English   中英

呈現所有DOM元素后,控制器或路由器中是否有要調用的鈎子?

[英]Is there a hook in either the controller or router to be called after all DOM elements have been rendered?

假設我想做一些jQuery的事情

// Do jQuery Stuff
$(document).ready(function(){
  $("button").click(function(){
    $("p").hide();
  });
});

而且我想將此代碼包含在路由或控制器中,我很確定自己無法實現,因為沒有鈎子函數(例如,IE model(), renderTemplate(), etc.可以保證所有DOM中的元素已安全地呈現。

現在,如果我在組件中執行此操作,我知道可以調用didInsertElement掛鈎,這將允許我運行上面的代碼。

我的用例

我想使用一個名為ScrollMagic的庫,它將需要jQuery進行配置。 除了我之外,其他人已經在路由和控制器中編寫了很多代碼。 我們可以輕松地將其移動到組件中(並且我們可能會這樣做),但是我仍然想問一下自己的好奇心。

路由或模型中是否有任何鈎子可以確保該模板的所有元素都已在DOM中呈現? 如果沒有,那是為什么呢? 畢竟,您可以在組件中使用該鈎子。

路由和控制器后沒有任何渲染鈎子

通常,您想要完成afterRender事情的方式是使用自定義元素修飾符(新): https : //github.com/emberjs/ember-render-modifiers (或將操作綁定到did-insert

或者,您可以制作一個僅定義了didInserElement掛鈎的無渲染組件。

因此,在您的模板中:

<BindButtonsToHideParagraphs />

然后在該組件內部:

export default class BindButtonsToHideParagraphs extends Component {
  didInsertElement() {
    document).ready(function(){
      $("button").click(function(){
        $("p").hide();
      });
  }
}

但是,根據您提供的jQuery,我強烈建議您對按鈕使用常規操作,並使用條件if / elses顯示/隱藏p標簽。

看起來像這樣:

<button {{action 'toggleParagraph'}}>click me</button>

{{#if this.showParagraph}}
  <p>text</p>
{{/if}}

export default class SomeComponent extends Component {
  @action
  toggleParagraph() {
    this.set('showParagraph', !this.showParagraph);
  }
}

或者,如果您使用的是Sparkles組件,則: https : //github.com/rwjblue/sparkles-component

<button {{action this.toggleParagraph}}>click me</button>

{{#if this.showParagraph}}
  <p>text</p>
{{/if}}

export default class SomeComponent extends Component {
  @tracked showParagraph = true;

  toggleParagraph() {
    this.showParagraph = !this.showParagraph;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM