Extending Javascript array with an event handler
Doyin Olarewaju 🇳🇬🇨🇦
Posted on July 27, 2018
I recently had to write a classifier algorithm that classified an array of items based on certain attributes. It was a pretty complicated dataset with an even more complicated set of constraints, but for the sake of this article i will keep it a simple.
Say we have the following dataset
[
{id:1, age:32},
{id:2, age:4},
{id:3, age:20},
{id:4, age:30}
]
Now, say we wish to find the oldest age and the sum of all ages. This can easily be done using a loop and some variables, but for the sake of this article I will use an event listener attached to the traditional javascript array to pull this off.
First Let's extend the array object
const MyArray = function (){
// this events object will be explained shortly
this.events = {}
}
So, simply I just created a function and called it my array then gave it an events object(or hashtable) that will hold all our events and callbacks in this form:
{eventName:callback_function}
Let's continue with creating the extended array
MyArray.prototype = []
MyArray.prototype.on = function (event, callback){
this.events[event] = callback
}
MyArray.prototype.push = function(args){
Array.prototype.push.call(this, args)
const eventName = 'push'
if(this.events[eventName]){
this.events[eventName](args)
}
}
In the snippet above we let our function inherit the properties of the array object using prototype inheritance.
The second block implements our event listener function. We call the function on, so we can do things like on('filter') etc. All this function does is take in the event (or event name) and a callback to execute once that event occurs. The function stores the event name as the key and the callback as the value in our events hashtable.
Lastly we make our own push method to put new items into our object. The next line uses the push method of the parent Array object, but by using call, we call push in the context of the current object. This works because our object has inherited from Array. That's all.
Testing our new object
So let's test this and see how it will work using the stated example data above.
const Arr = new MyArray()
let sum = 0;
let oldest = 0;
Arr.on('push', function (e){
sum += e.age
oldest = (e.age > oldest ? e.age:oldest)
})
for (let data of dataSet){
Arr.push(data)
}
console.log(sum, oldest)
And that's it.
Posted on July 27, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.