简体   繁体   English

Ember js动态操作以使用{{#if}}助手来切换显示

[英]Ember js dynamic action to toggle display using {{#if}} helper

I'm using some very simple actions to toggle content boxes in Ember: (Working example here: http://emberjs.jsbin.com/heyena/edit?html,css,js,output ). 我正在使用一些非常简单的操作来切换Ember中的内容框:(此处的工作示例: http ://emberjs.jsbin.com/heyena/edit?html,css,js,output)。

index.hbs (Template) index.hbs (模板)

 <span {{action 'toggleBoxOne'}}>Toggle Box One</span> <span {{action 'toggleBoxTwo'}}>Toggle Box Two</span> {{#if One}} <h3>Box 1</h3> {{/if}} <div class="clr"></div> {{#if Two}} <h3>Box 2</h3> {{/if}} 

index.js (Controller) index.js (控制器)

 actions: { toggleBoxOne: function() { this.set('Two', false); var showBox = this.get('One'); if (showBox === false) { this.set('One', true); } else { this.set('One', false); } }, toggleBoxTwo: function() { this.set('One', false); var showBoxTwo = this.get('showBoxTwo'); if (showBoxTwo === false) { this.set('showBoxTwo', true); } else { this.set('showBoxTwo', false); } }, }, One: false, Two: false 

I'm trying to create a single action, which can toggle different boxes based on arguments passed in the action handler: 我正在尝试创建一个动作,该动作可以根据在动作处理程序中传递的参数切换不同的框:

 <span {{action 'toggleBox' 'One'}}>Toggle Box One</span> <span {{action 'toggleBox' 'Two'}}>Toggle Box Two</span> 
I would like to do something like the below, 我想做下面的事情,

 toggleBox: function(boxName) { var thisBox = boxName; if (thisBox === true) { this.set(thisBox, false); } else { this.set(thisBox, true); } }, thisBox: false, 
Is it possible to do this, while ensuring that showing one content box causes all others to disappear? 是否可以这样做,同时确保显示一个内容框会导致所有其他框消失?

You can do something very close to what you wanted: 您可以执行非常接近所需的操作:

toggleBox: function(boxName) {
  var thisBox = this.get(boxName);
    if (thisBox === true) {
      this.set(boxName, false);
    } else {
      this.set(boxName, true);
  }
}

But it's much easier to just do 但是做起来要容易得多

this.set(boxName, !this.get(boxName))

which can be written even more compactly (and a bit more efficiently) as 可以更紧凑地(并且更有效地)编写为

this.toggleProperty(boxName)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM