我如何将我的测验的所有选项设置为活动:false点击

How do I set all options of my quiz to active: false on click?

本文关键字:设置 选项 活动 点击 false 我的      更新时间:2023-09-26

我正在尝试构建一个带有多项选择选项的问题(最终是一个测验)。当用户单击某个选项时,活动类被设置为true,并为该选项插入红色背景。我想帮助的是,如果用户决定点击另一个选项。之前的活动选项应该更改为active: false,新选项应该更改为active: true。这是我的第一个Ember.js应用程序,所以如果有更好的方法,我洗耳恭听。

 var IndexRoute = Ember.Route.extend({
   model: function() {
     return Ember.A([
      {
        question: "What's up?",
        options: [
          {
            text: "option a",
            active: false
          },
          {
            text: "option b",
            active: false
          }
        ]
      },
      {
        question: "How many?",
        options: [
          "one",
          "two"
        ]
      }
     ]);
   }
 });

index.hbs

{{#each model}}
  {{quiz-question section=this}}
{{/each}}

quiz-question.hbs

{{#with section}}
  {{question}}
  {{#each options}}
    {{quiz-option active=active text=text}}
  {{/each}}
{{/with}}
{{yield}}

quiz-option.hbs

<div {{bind-attr class="active"}}>{{text}}</div>
{{yield}}

quiz-option.js

export default Ember.Component.extend({
  click: function () {
    console.log('asdf', this.get('text'));
    this.set('active', true);
  }
});

app.css

html, body {
  margin: 20px;
}
.active {
  background-color: red;
}

您可以使用sendAction将操作传递给父级,在父级中它可以迭代集合并将所有其他项设置为false。

App.QuizOptionComponent = Ember.Component.extend({
  click: function () {
    this.set('active', true);
    this.sendAction('killFriendsExcept', this.get('text'));
  }
});
{quiz-option active=active text=text  killFriendsExcept='resetChildrenExcept'}}

App.QuizQuestionComponent = Ember.Component.extend({
  actions: {
    resetChildrenExcept: function(except){
      this.get('section.options').forEach(function(item){
        if(Em.get(item, 'text')!=except){
          Em.set(item, 'active', false);
        }
      });
    }
  }
});
http://emberjs.jsbin.com/jitezago/1/edit