【问题标题】:Ember js controlling class bindings in repeating componentEmber js控制重复组件中的类绑定
【发布时间】:2015-10-12 15:07:58
【问题描述】:

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

下面的代码成功地将“活动”类添加到单击的标题元素中。

当单击一个新标题时,如何从所有以前的标题中删除“活动”类(这样只有一个标题使该类处于活动状态)?

我最初尝试在控制器上执行此操作,但我不知道如何在每个循环中的一个实例上设置 isActive 属性。

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

【问题讨论】:

    标签: javascript ember.js


    【解决方案1】:

    由于您为您的逻辑制定了解决方法: Ember js get array index of clicked element in an each loop, and filter with 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>
    

    【讨论】:

    • 非常感谢 - 我可以清楚地看到它是如何工作的。但是有一个小问题 - 因为 activePost 最初设置为 null,所以该操作的第一次运行给出了错误 Property set failed: object in path "activePost" could not be found or was destroyed。 是否可以在输入路由时将数组中的第一个对象设置为activePost?
    • 当然,是的,我也看到了这个问题 =D 一秒改变
    • 我不再在每个循环中使用组件,所以我不确定 didInsertElement 是否有帮助?
    • @AJP 哦,年,完全忘记了。让我想一个更好的。
    • .on(init) 怎么样?类似以下的函数:if (activePost === null) {Set first object in the categorisedPosts array to be activePost, and set isActive to true on that object}
    【解决方案2】:

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

    所以,在控制器中定义“activeIndex”属性:

    activeIndex: null
    

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

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

    然后,将“全局”变量传递给每个组件:

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

    并在 TitleComponent 中的“setActive”操作中更改 activeIndex 值:

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

    附:请考虑清除“bind-attr”助手。很久以前就被弃用了。

    【讨论】:

      猜你喜欢
      • 2016-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-05
      • 2020-11-07
      • 1970-01-01
      相关资源
      最近更新 更多