是否可以为普通的JavaScript Array对象实现" addEventListener"类型的功能?



我正在做一个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`)
})

相关内容

  • 没有找到相关文章

最新更新