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.
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]"
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
JavaScript Array push()The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.
To add the event listener to the multiple elements, first we need to access the multiple elements with the same class name or id using document. querySelectorAll() method then we need to loop through each element using the forEach() method and add an event listener to it.
push() The push() method adds one or more elements to the end of an array and returns the new length of the array.
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); }; };
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);
The only sensible way to do this is to write a class that wraps around an array:
function EventedArray(handler) { this.stack = []; this.mutationHandler = handler || function() {}; this.setHandler = function(f) { this.mutationHandler = f; }; this.callHandler = function() { if(typeof this.mutationHandler === 'function') { this.mutationHandler(); } }; this.push = function(obj) { this.stack.push(obj); this.callHandler(); }; this.pop = function() { this.callHandler(); return this.stack.pop(); }; this.getArray = function() { return this.stack; } } var handler = function() { console.log('something changed'); }; var arr = new EventedArray(handler); //or var arr = new EventedArray(); arr.setHandler(handler); arr.push('something interesting'); //logs 'something changed'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With