Ember js在重复组件中控制类绑定

Ember js controlling class bindings in repeating component

本文关键字:控制 绑定 组件 js Ember      更新时间:2023-09-26

我有一个在每个循环中重复的组件。该组件仅显示文章的标题(可能有数百个)。

下面的代码成功地将类"active"添加到被单击的标题元素中。

我怎么能删除类'活动'从所有以前的标题,当一个新的点击(所以只有一个标题曾经有类活动)?

我最初尝试在控制器上这样做,但我无法弄清楚如何在每个循环中的一个实例上设置isActive属性。

Template.hbs:

{#each posts as |post index item|}}
  {{title-component data=post index=index}}
{{/each}}

title-component.hbs:

<a {{bind-attr class="isActive:active"}}{{action 'setActive' index}}>{{data.title}}</a>

title-component.js

actions: {
  setActive: function(index) {
    this.set('isActive', true);
  },
},

既然你为你的逻辑做了一个变通:Ember js在每个循环中获取被点击元素的数组索引,并使用它进行筛选

我在此基础上创造了活跃度。

updateFullText: function(post) {
     this.set('activePost.isActive', false); // First lose previous activeness
     this.set('activePost', post); // Active post gets re-valuated
     this.set('activePost.isActive', true);  // Activate new item
}


   <div class="left-section">
      {{#each categorisedPosts |as| post}}
        <span class="{{if post.isActive 'activeClass'}}> {{post.description}} </span>
     {{/each}}
   </div>

您可以通过多种方式设置活跃度。但是考虑到你已经做了一些工作,我将稍微改进一下你的解决方案。你可以在TitleComponent中定义isActive属性为计算属性,它依赖于控制器中的activeIndex变量。

那么,在控制器中定义'activeIndex'属性:

activeIndex: null

然后,在titlecomponent中定义isActive属性:

isActive: Ember.equal('activeIndex', 'index')

然后,将'global'变量传递给每个组件:

{#each posts as |post index item|}}
  {{title-component data=post index=index activeIndex=activeIndex}}
{{/each}}

并更改titlecomcomponent中'setActive'动作中的activeIndex值:

actions: {
  setActive: function(index) {
    this.set('activeIndex', index);
  },
}

注:请考虑消灭"捆绑"助手。