Ember js - 切换传递给动作的当前和上一个值

时间:2015-10-05 09:54:09

标签: javascript ember.js

当点击三个按钮时,我有以下简单模式来切换三个不同div的可见性:

模板/ index.hbs

<button {{action 'toggleBox' 'boxOne'}}>One</button>
<button {{action 'toggleBox' 'boxTwo'}}>Two</button>
<button {{action 'toggleBox' 'boxThree'}}>Three</button>
{{#if boxOne}}
<div>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
{{/if}} 
{{#if boxTwo}}
<div>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
{{/if}} 
{{#if boxThree}}
<div>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
{{/if}}

控制器/ index.js

toggleBox: function(boxName) {
  this.toggleProperty(boxName);
},

问题是我一次只需要显示1个框 - 如果 boxOne 可见,则点击 boxTwo 应显示 boxTwo 并隐藏 boxOne

我试图在切换值后将属性名称保存在变量中,以便在打开其他框时将其设置为false,但我无法获得正确的模式。

toggleBox: function(boxName) {
  /***Here I would like to set the previous value of boxName to false***/
  this.toggleProperty(boxName);
  //put the current value of boxName in a variable to use in the next run of the action.
  this.set('currentBox', boxName);
  var current = this.get('currentBox');
},

2 个答案:

答案 0 :(得分:1)

也许这种处理new_enum.to_a属性的方式不那么苛刻。

currentBox

答案 1 :(得分:0)

找到解决方案:

&#13;
&#13;
toggleBox: function(boxName) {
  var current = this.get('currentBox');
  if ((current) && (current !== boxName)) {
    this.set(current, false);
  };
  this.toggleProperty(boxName);
  this.set('currentBox', boxName);
},
&#13;
&#13;
&#13;

以上创建了一个属性&#39; currentBox&#39;当下一个动作运行时可用。在if语句中使用 this.toggleProperty(current); 非常重要,以避免在第一次运行操作时出现错误。