目录

使用willDestroyElement分离和拆除(Detaching and Tearing Down with willDestroyElement)

您可以通过触发willDestroyElement挂钩从DOM中删除组件元素。

语法 (Syntax)

import Ember from 'ember';
export default Ember.Component.extend ({
   ...
   willDestroyElement() {
      //code here    
   },
   ...
})

例子 (Example)

下面给出的示例描述了使用willDestroyElement钩子,它从DOM中删除了组件元素。 使用名称索引创建一个控制器并从app/controller/打开文件以添加以下代码 -

import Ember from 'ember';
export default Ember.Controller.extend ({
   showComponent: true,
   laterCount: 0,
   buttonText: Ember.computed('showComponent', function() {
      let showing = Ember.get(this, 'showComponent');
      if (showing) {
         return 'Remove';
      } else {
         return 'Add';
      }
   }),
   actions: {
      toggleComponent() {
         this.toggleProperty('showComponent');
      },
      updateLaterCount() {
         Ember.set(this, 'laterCount', Ember.get(this, 'laterCount') + 1);
      }
   }
});

创建一个名为post-action的组件,该组件将在app/components/下定义。

打开post-action.js文件并添加以下代码 -

import Ember from 'ember';
export default Ember.Component.extend ({
   runLater: null,
   didInsertElement() {
      let timeout = Ember.run.later(this, function() {
         Ember.Logger.log('fired this after 1 seconds...');
         this.sendAction();
      }, 500);
      Ember.set(this, 'runLater', timeout);
   },
   willDestroyElement() {
      Ember.run.cancel(Ember.get(this, 'runLater'));
   }
});

现在使用以下代码打开组件模板文件post-action.hbs -

<h2>IoWiki</h2>

打开index.hbs文件并添加以下代码 -

<h5>Count for clicks: {{laterCount}}</h5>
<button {{action 'toggleComponent'}}>{{buttonText}}</button>
{{#if showComponent}}
   {{post-action action="updateLaterCount"}}
{{/if}}
{{outlet}}

输出 (Output)

运行ember服务器; 你会收到以下输出 -

Ember.js组件将desDestroyElement Attr

最初的点击次数为1.当您单击“ Remove button ,它将删除文本 -

Ember.js组件将desDestroyElement Attr

接下来,单击“ Add按钮,它将增加点击次数并显示文本 -

Ember.js组件将desDestroyElement Attr
↑回到顶部↑
WIKI教程 @2018