summaryrefslogtreecommitdiff
path: root/addons/mail/static/src/model/model_field_command.js
blob: f4e59a957f37ab208abbab9ea177c513415d30e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
odoo.define('mail/static/src/model/model_field_command.js', function (require) {
'use strict';

/**
 * Allows field update to detect if the value it received is a command to
 * execute (in which was it will be an instance of this class) or an actual
 * value to set (in all other cases).
 */
class FieldCommand {
    /**
     * @constructor
     * @param {function} func function to call when executing this command. 
     * The function should ALWAYS return a boolean value 
     * to indicate whether the value changed.
     */
    constructor(func) {
        this.func = func;
    }

    /**
     * @param {ModelField} field
     * @param {mail.model} record
     * @param {options} [options]
     * @returns {boolean} whether the value changed for the current field
     */
    execute(field, record, options) {
        return this.func(field, record, options);
    }
}

/**
 * Returns a clear command to give to the model manager at create/update.
 */
function clear() {
    return new FieldCommand((field, record, options) =>
        field.clear(record, options)
    );
}

/**
 * Returns a decrement command to give to the model manager at create/update.
 *
 * @param {number} [amount=1]
 */
function decrement(amount = 1) {
    return new FieldCommand((field, record, options) => {
        const oldValue = field.get(record);
        return field.set(record, oldValue - amount, options);
    });
}

/**
 * Returns a increment command to give to the model manager at create/update.
 *
 * @param {number} [amount=1]
 */
function increment(amount = 1) {
    return new FieldCommand((field, record, options) => {
        const oldValue = field.get(record);
        return field.set(record, oldValue + amount, options);
    });
}

return {
    // class
    FieldCommand,
    // shortcuts
    clear,
    decrement,
    increment,
};

});