简体   繁体   中英

Ember js - toggle current and previous value passed to an action

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'); }, 

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')
/* ... */

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.

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