在{{#each}} - Ember中独立于其他行切换行

时间:2017-05-16 01:26:32

标签: javascript ember.js

我的控制器中有一大堆代码可以在第一行输出我想要的所有内容。第二行将在单击操作时可用。但是,我正在尝试这样做,以便当我单击显示的任何行时,它将仅显示给定行的第二行。不是所有其他人的第二排。

这是在我的模板中。

{{#each chosenSomething as |something|}}
   <tr class='main' {{action 'toggleHelp'}}>
     <td>{{something.this}}</td>
     <td>{{something.that}}</td>
     <td>{{something.hey}}</td>
     <td>{{something.you}}</td>
   </tr>
   {{#if isDisplay}}
     <tr class='help'>
       <td class='instruction'></td>
       <td class='video'></td>
     </tr>
   {{/if}}
{{/each}}

这是我的JS动作。

toggleHelp() {
    this.toggleProperty('isDisplay');
},

我知道如何使用jQuery来解决这个问题,但我想知道Ember做这种行为的方式。我考虑过包含索引,但不确定应该如何编写索引。

2 个答案:

答案 0 :(得分:0)

增加chosenSomething的每个元素以包含打开/关闭状态。 然后你就可以拥有:

{{#each chosenSomething as |something|}}
  <tr class='main' {{action 'toggleHelp' something}}>
    <td>{{something.this}}</td>
    <td>{{something.that}}</td>
    <td>{{something.hey}}</td>
    <td>{{something.you}}</td>
  </tr>
  {{#if something.isDisplay}}
  <tr class='help'>
   <td class='instruction'></td>
   <td class='video'></td>
  </tr>
  {{/if}}
{{/each}}

和JS:

toggleHelp(something) {
    Ember.set(something, 'isDisplay', !something.isDisplay);
}

如果您不想修改原始数据,可以让计算属性生成相应的数据,例如:

chosenSomethingWithState() {
    return (this.get('chosenSomething') || []).map((item)=>{isDisplay:false, item})
}.property('chosenSomething')

并相应调整模板

答案 1 :(得分:0)

我建议制作一个组件并将切换器放在其中。

https://ember-twiddle.com/e6ccad3d2ffdc4a9d627db12a1317fa5?openFiles=templates.components.toggle-thing.hbs%2Ctemplates.components.toggle-thing.hbs

// toggle-thing.hbs
<header {{action 'toggleAnswer'}}>
    {{data.question}}
</header>

{{#if open}}
  <footer>
    {{data.answer}}
  </footer>
{{/if}}


// toggle-thing.js
import Ember from 'ember';

export default Ember.Component.extend({
  // tagName: 'tr', // or whatever if you like
  // classNames: ['thing', 'row', 'etc'], // smooth out the template a bit later...
  open: false, // default
  actions: {
    toggleAnswer() {
      this.toggleProperty('open');
      console.log( this.get('open') );
    },
  },
});


// application.hbs or wherever you want to list the things
<ul class='thing-list'>
  {{#each model as |thing|}}
    <li class='thing'>
      {{toggle-thing data=thing}}
    </li>
  {{/each}}
</ul>

有一个“东西”模型,并且正在为模型钩子提供一些问题答案。

import Ember from 'ember';

var data = [
  {
    question: "How to be funny",
    answer: "Stand on your head",
  },
  {
    question: "How to be smart",
    answer: "Just listen more often.",
  },
];

export default Ember.Route.extend({

  model() {
    return data;
  },

});

Ember指南有一个切换示例:https://guides.emberjs.com/v2.13.0/tutorial/simple-component/

相关问题