javascript - 构建数组监听器

标签 javascript

有没有办法将监听器附加到另一个进程正在构建的数组,以便当 array.length 达到特定值时,监听器执行回调并触发适当的代码?

fooArray = [];
// another code adds objects to array

if (fooArray.length = 5) {
  // callback
} else {
  // continue checking fooArray.length
}

最佳答案

你必须使用自己的方法来改变数组

Array.prototype.myPush = function () {

    this.push.apply( this, arguments );
    if ( this._binder && this._binder.test.call( this ) ) {
        this._binder.callback.call( this );
    }

}

Array.prototype.bind = function (tester, callback) {
    this._binder = {
        test: tester,
        callback: callback
    };
}

var arr = [4, 6, 9, 20];
arr.bind( function () {
    return this.length >= 5;
}, function () {
    console.log( "Array has exceeded" );
} );

arr.myPush( 40 );

关于javascript - 构建数组监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20305442/

相关文章:

javascript - 如何将具有特定功能的输入文本字段转换为执行相同功能的文本区域?

javascript - 单页多个进度条

javascript - Twilio - 如何针对每个电话号码发送具有不同正文的批量短信?

javascript - insidehtml 提交按钮

javascript - 我怎样才能创建一个阴影效果完全沿 Canvas 的顶部以外的所有侧面运行?

javascript - 数据表分页未出现

javascript - 使用 HTML 或 CSS 动态调整 Logo 大小

javascript - 使用数组辅助函数具有唯一值的数组

javascript - 在什么情况下我们必须使用本地存储而不是cookies?

javascript - 从输入焦点事件启动时,JQuery UI 对话框未关闭