有没有办法将监听器附加到另一个进程正在构建的数组,以便当 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/