1 | module.exports = function(client, onChange) {
|
2 | var canCancel = !!client.cancel;
|
3 |
|
4 | return function createAction(name) {
|
5 | var request;
|
6 |
|
7 | function action(changeset, actionDone) {
|
8 | if (!canSubmit(changeset)) return null;
|
9 |
|
10 | return function submission(done) {
|
11 | if (!canSubmit(changeset)) return;
|
12 | action.canSubmit = false;
|
13 | action.canReset = canCancel;
|
14 | action.isSubmitting = true;
|
15 |
|
16 | request = client.submit(changeset, function(err, response) {
|
17 | request = null;
|
18 | action.canReset = true;
|
19 | action.isSubmitting = false;
|
20 | action.isFinished = true;
|
21 | action.error = err;
|
22 | action.response = response;
|
23 | onChange(action, name);
|
24 | if (typeof actionDone === 'function') actionDone(action);
|
25 | if (typeof done === 'function') done(action);
|
26 | });
|
27 |
|
28 | onChange(action, name);
|
29 | };
|
30 | }
|
31 |
|
32 | function canSubmit(changeset) {
|
33 | return !(!changeset || !changeset.isValid || action.isSubmitting || action.isFinished);
|
34 | }
|
35 |
|
36 | function cancel() {
|
37 | if (canCancel) {
|
38 | client.cancel(request);
|
39 | return true;
|
40 | } else {
|
41 | return false;
|
42 | }
|
43 | }
|
44 |
|
45 | action.reset = function(shouldUpdate) {
|
46 | if (action.isSubmitting && !cancel()) return false;
|
47 | action.canSubmit = true;
|
48 | action.canReset = true;
|
49 | action.isSubmitting = false;
|
50 | action.isFinished = false;
|
51 | delete action.error;
|
52 | delete action.response;
|
53 | if (shouldUpdate !== false) onChange(action, name);
|
54 | return true;
|
55 | };
|
56 |
|
57 | action.reset(false);
|
58 |
|
59 | return action;
|
60 | };
|
61 | };
|