代码之家  ›  专栏  ›  技术社区  ›  Cameron

在呈现所有DOM元素后,控制器或路由器中是否有要调用的钩子?

  •  0
  • Cameron  · 技术社区  · 7 年前

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

    我想在路由或控制器中包含这段代码,我很确定我不能实现它,因为没有钩子函数(即。 model(), renderTemplate(), etc.

    现在,如果我在一个组件中这样做,我知道我可以调用 didInsertElement hook,这样我就可以运行上面的代码了。

    我的用例

    我想使用一个名为ScrollMagic的库,它需要jQuery来配置。我以外的人已经在路由和控制器中编写了很多代码。我们可以很容易地将它移动到一个组件(我们可能会),但出于我自己的好奇心,我仍然想问这个问题。

    问题

    1 回复  |  直到 7 年前
        1
  •  2
  •   NullVoxPopuli    7 年前

    路由和控制器没有任何后渲染挂钩

    afterRender https://github.com/emberjs/ember-render-modifiers (或将一项行动约束于 did-insert )

    因此,在模板中:

    <BindButtonsToHideParagraphs />
    

    然后在该组件内部:

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

    不过,根据您提供的jQuery,我强烈建议您在按钮上使用正常操作,并使用条件if/else来显示/隐藏 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);
      }
    }
    

    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;
      }
    }