Ember js controlling class bindings in repeating component

房东的猫 提交于 2020-01-07 01:49:18

问题


I have a component which is repeating inside an each loop. The component simply displays the title of a post (There could potentially be hundreds).

The code below is successfully adding the class 'active' to a title element which is clicked.

How can I remove class 'active' from all previous titles when a new one is clicked (So that only one title ever has the class active)?

I originally tried doing this on the controller, but I couldn't work out how to set the isActive property on one instance in the each loop.

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

回答1:


Since you made a workaround for your logics : Ember js get array index of clicked element in an each loop, and filter with it

I made activeness based on it.

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>



回答2:


You could set activeness in many ways. But considering you already done some work, I'll just slightly improve your solution. You can define isActive property in TitleComponent as computed property that depends on 'activeIndex' variable from controller.

So, define 'activeIndex' property in controller:

activeIndex: null

Then, define isActive property in TitleCompoenent:

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

Then, pass the 'global' variable to each component:

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

And change activeIndex value in 'setActive' action in TitleComponent:

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

P.S. Please, consider to wipe out 'bind-attr' helper. It's been deprecated a long ago.



来源:https://stackoverflow.com/questions/33084416/ember-js-controlling-class-bindings-in-repeating-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!