Use Promise for popup
Prasanna Vijayan
Posted on September 15, 2019
There are lot of things you can do with Promise. Today, I will share my experience on using promise for modal which I recently learned.
If you don't know much about EmberJs or Promise. Please visit EmberJS and
Promise) to get your basics up
Why Promise?
https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261
Prerequisites
ember install ember-bootstrap
ember generate ember-bootstrap --preprocessor=sass
If you want to use less instead of sass use --preprocesor=less
. For other config, please check here
Steps
- Create your component using
ember generate component promise
- promise.js
import Component from '@ember/component';
export default Component.extend({
// It's important to have response undefined instead of boolean
response : undefined,
show : false,
actions: {
promiseClicked() {
new Promise( respond => {
this.set( 'show', true );
this.addObserver( 'response', function observer() {
this.removeObserver( 'response', observer );
respond( this.get( 'response' ) )
});
}).then( proceed => {
if ( proceed ) {
console.log( proceed );
} else {
console.log( proceed );
}
this.setProperties({ 'show': false, 'response': undefined });
});
},
response( bool ) {
this.set( 'response', bool );
}
},
});
Make sure variable response is set to undefined after removing observer.
- promise.hbs
<BsButton @onClick={{action 'promiseClicked'}}> Promise </BsButton>
<BsModal
@open={{show}}
@onSubmit={{action "response" true}}
@onHidden={{action "response" false}} as |modal|>
<modal.header>
<h4 class="modal-title">
Custom Dialog
<div class="badge">2</div>
</h4>
</modal.header>
<modal.body>
Promise Example?
Check console when you click "Cancel or Save".
</modal.body>
<modal.footer>
<BsButton @onClick={{action "response" false}}>Cancel</BsButton>
<BsButton @type="success" @onClick={{action "response" true}}>Save</BsButton>
</modal.footer>
</BsModal>
That's it. Thanks!
💖 💪 🙅 🚩
Prasanna Vijayan
Posted on September 15, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.