Reputation: 545
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>
toggleBox: function(boxName) {
var thisBox = boxName;
if (thisBox === true) {
this.set(thisBox, false);
} else {
this.set(thisBox, true);
}
}, thisBox: false,
Upvotes: 0
Views: 464
Reputation:
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)
Upvotes: 3