user7474631
user7474631

Reputation:

Ember Disable button while an action is completing its process

template

{{input type="email" value=email placeholder="email"}}
<button {{action "addUser"}} type="submit">Add</button>

controller

export default Controller.extend({
    actions: {
        addUser: function(){
            //some codes here
            $.ajax({
                //some codes here
            }).then(()=>{
                alert("success");
            });
        }
    }
});

When I call press the button and call the function addUser I need to disable the button until the whole function is finished execution

Please help..!

Upvotes: 0

Views: 690

Answers (1)

Gennady Dogaev
Gennady Dogaev

Reputation: 5991

There are two ways of doing that.

First - maintain state manually

This means you should have a property on your controller and set it to true when task is running

export default Controller.extend({
    actions: {
        addUser: function(){
            this.set('addUserRunning', true);
            //some codes here
            $.ajax({
                //some codes here
            }).then(()=>{
                alert("success");
            }).always(() => {
                this.set('addUserRunning', false);
            });
        }
    }
});

{{input type="email" value=email placeholder="email"}}
<button type="submit" disabled={{addUserRunning}} {{action "addUser"}}>Add</button>

Second (recommended by me) - use ember-concurrency

There is an addon called ember-concurrency. You need to look through the docs to understand how to use it. Instead of action you will use task and task has properties for it's state.

It will be something like this:

import { task } from 'ember-concurrency';

export default Controller.extend({
    addUser: task(function* () {
        //some codes here
        yield $.ajax({
           //some codes here
        });
        alert("success");
    }).drop()
});

{{input type="email" value=email placeholder="email"}}
<button type="submit" disabled={{addUser.isRunning}} onclick={{perform addUser}}>Add</button>

Upvotes: 4

Related Questions