Reputation: 545
I have the following simple pattern to toggle the visibility of three different divs when three buttons are clicked:
templates/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}}
controllers/index.js
toggleBox: function(boxName) {
this.toggleProperty(boxName);
},
The problem is that I need only 1 box to show at a time- if boxOne is visible, then clicking boxTwo should show boxTwo and hide boxOne.
I have tried to save the property name in a variable after the value is toggled, so that it can be set to false when a different box is opened, but I can't get the right pattern.
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');
},
Upvotes: 0
Views: 187
Reputation: 1264
Maybe this way of handling the currentBox
attribute is a bit less hackish.
currentBox: '',
toggleBox: function(boxName) {
this.set('currentBox', boxName);
},
boxOneIsActive: function() {
return this.get('currentBox') === 'boxOne');
}.property('currentBox')
/* ... */
Upvotes: 2
Reputation: 545
Found the solution:
toggleBox: function(boxName) {
var current = this.get('currentBox');
if ((current) && (current !== boxName)) {
this.set(current, false);
};
this.toggleProperty(boxName);
this.set('currentBox', boxName);
},
The above creates a property 'currentBox' which is available when the action next runs. It's important to have this.toggleProperty(current); in an if statement to avoid an error when the action runs the first time.
Upvotes: 0