灰烬|设置特定元素的css类

时间:2017-02-19 02:08:50

标签: javascript css ember.js

我在Ember中渲染一些模型参数,它应该像一个复选框。因此,点击元素的css类应该改变,以指示状态(例如,活动时为绿色)。 目前,只有一个被渲染的元素在单击一个时更改了它们的类。 我怎样才能只更改真正点击的元素的css类?我以为。这会照顾到。

那是我的视图模板:

  {{#each model as |attributes|}}
  {{#each attributes.identifiers as |identifier| }}
    <div class="col-element">
      <div class="checkelement {{state}}" {{action "includeToExport" identifier}}>
        <p>{{identifier}}</p>
      </div>
    </div>
  {{/each}}
{{/each}}

控制器中的动作:

includeToExport: function(identifier){
var state = this.get('state');
if (state == 'activated'){
  this.set('state','');
  // and do something with identifier
}
else {
  this.set('state', 'activated');
  // and do something with identifier
}},

CSS:

.checkelement.activated {background-color:#4CAF50; }

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

如果你想为每个项目设置一个单独的状态,一个选项是创建一个代表每个标识符的组件并在那里移动状态控件。您可以将其视为将{{#each}}...{{/each}}之间的所有代码移动到其自己的组件中。这将允许您封装每个标识符的状态控件:

{{#each model as |attributes|}}
  {{#each attributes.identifiers as |identifier| }}
    {{my-identifier identifier=identifier
                    includeToExportAction=(action "includeToExport")}}
  {{/each}}
{{/each}}

该组件看起来像

// components/my-identifier
export default Ember.Component.extend({
  // passed in
  identifier: null,
  includeToExportAction: null,

  // local
  state: '', // <-- here you set the initial value for the state
  classNames: ['col-element'],

  actions: {
    setState() {
      // state-control is now local to each component
      // and thus unique for each identifier
      const state = this.get('state');
      if (state == 'activated'){
        this.set('state','');
      } else {
        this.set('state', 'activated')
      }

      // send the identifier and the updated state to the parent
      this.get('includeToExportAction')(
        this.get('state'),
        this.get('identifier')
      )
    }
  }
});

组件模板

// templates/components/my-identifier
<div class="checkelement {{state}}" {{action "setState"}}>
  <p>{{identifier}}</p>
</div>

现在你的控制器不需要在includeToExport中设置任何状态,因为它现在从my-identifier组件传递:

includeToExport(identifier, state){
  if (state == 'activated'){
    // do something with identifier
  }
  else {
    // do something with identifier
  }
}