Javascript:将事件侦听器附加到Array以进行Push()事件 [英] Javascript: Attach Event Listener to Array for Push() Event

查看:106
本文介绍了Javascript:将事件侦听器附加到Array以进行Push()事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法知道用户何时(通过push())将项目推送到数组?

Is there a way to know when a user has pushed (via push()) an item onto an array?

基本上我有一个异步脚本,允许用户将命令推送到数组上。加载脚本后,它会执行命令。问题是,用户可能会在我的脚本运行后将其他命令推送到阵列上,我需要在发生这种情况时收到通知。请记住,这只是用户自己创建的常规数组。谷歌分析做了类似的事情。

Basically I have an asynchronous script that allows the user to push commands onto an array. Once my script loads, it execute the commands. The problems is, the user may push additional commands onto the array after my script has already run and I need to be notified when this happens. Keep in mind this is just a regular array that the user creates themselves. Google Analytics does something similar to this.

我也发现这是我认为谷歌这样做的地方,但我不太了解代码:Aa = function( k){
返回Object.prototype [ha] .call(Object(k))==[object Array]

I also found this which is where I think Google does it, but I don't quite understand the code: Aa = function (k) { return Object.prototype[ha].call(Object(k)) == "[object Array]"

我也发现了一个很棒的示例似乎涵盖了基础,但我不能让我添加的推送方法正常工作:
http:// jsbin.com/ixovi4/4/edit

I also found a great example which seems to cover the bases, but I can't get my added push method to work correctly: http://jsbin.com/ixovi4/4/edit

推荐答案

您可以使用覆盖推送的'eventify'功能传递的数组。

You could use an 'eventify' function that overrides push in the passed array.

var eventify = function(arr, callback) {
    arr.push = function(e) {
        Array.prototype.push.call(arr, e);
        callback(arr);
    };
};

在以下示例中,应该引发3个警报,因为这是事件处理程序(回调)执行的操作在调整之后。

In the following example, 3 alerts should be raised as that is what the event handler (callback) does after eventify has been called.

var testArr = [1, 2];

testArr.push(3);

eventify(testArr, function(updatedArr) {
  alert(updatedArr.length);
});

testArr.push(4);
testArr.push(5);
testArr.push(6);

这篇关于Javascript:将事件侦听器附加到Array以进行Push()事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆