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

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

问题描述

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

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

基本上,我有一个异步脚本,该脚本允许用户将命令推入数组。脚本加载后,它将执行命令。问题是,用户可能在我的脚本运行后将其他命令推入阵列,并且在发生这种情况时需要通知我。请记住,这只是用户创建自己的常规数组。 Google Analytics(分析)与此类似。

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.

我也发现这是我认为Google所做的事情,但是我不太理解代码:

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]"

我也找到了一个很好的例子,似乎涵盖了基础,但我可以无法让我添加的push方法正常工作:
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函数来覆盖已传递数组中的push。

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);

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

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