我正在做一个JS的可视化库,想知道这样的东西是否可能?
const my_arr = [];
my_arr.addEventListener('push', (item) => {
console.log(`${item} was pushed in my_arr`);
})
my_arr.push(3); //should give "3 was pushed in my_arr"
你可以重载push方法:
const my_arr = [];
my_arr.real_push = my_arr.push; // save my_arr.push real method
my_arr.push = function( item ) // overload my_arr.push method
{
my_arr.real_push( item ); // perform the push...
console.log(`${item} was pushed in my_arr`);
}
/// test :
my_arr.push(3); // 3 was pushed in my_arr
my_arr.push(55); // 55 was pushed in my_arr
console.log( my_arr)
参见自定义事件的文档。
document.body.addEventListener('addItem', e => {
this.my_arr.push(e.detail.item)
cosole.log(`${item} was pushed in my_arr`)
})