Detecting changes in a Javascript array using the Proxy object

后端 未结 2 786
醉梦人生
醉梦人生 2020-11-29 04:44

It is relatively trivial to watch for changes in an array in Javascript.

One method I use is like this:

// subscribe to add, update, delete, and spli         


        
2条回答
  •  既然无缘
    2020-11-29 05:11

    You can do somthing like this

    new Proxy([], {
        get(target, prop) {
            const val = target[prop];
            if (typeof val === 'function') {
                if (['push', 'unshift'].includes(prop)) {
                    return function (el) {
                        console.log('this is a array modification');
                        return Array.prototype[prop].apply(target, arguments);
                    }
                }
                if (['pop'].includes(prop)) {
                    return function () {
                        const el = Array.prototype[prop].apply(target, arguments);
                        console.log('this is a array modification');
                        return el;
                    }
                }
                return val.bind(target);
            }
            return val;
        }
    });
    

提交回复
热议问题