简体   繁体   中英

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 ).

index.hbs (Template)

 <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)

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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