A simple JavaScript observable array

Working with JavaScript is very popular in SharePoint enviroment today. Unfortunately, people are looking in other external libraries to achieve functionality they already have, but they are not aware of it. Today, I have decided to present how a SharePoint programmer can make an observable array by using what any web forms based technology already has.
I will take as an example an array containing my names. Initially I will include only two names in it and I will add the other in an observable manner also executing in the same time a handler I will attach to change event.

var arr = ['Andrei', 'Popescu'];

After I have declared my array, is time to make it observable. And of course, as there is no point to make it observable without executing an action when is modified, I will attach a handler to collection change event.

var obsvervableArr = Sys.Observer.makeObservable(arr);
Sys.Observer.addCollectionChanged(obsvervableArr, function(target) {

And now, here comes the magic. To add an item to my array in an observable manner, I simply need to call static method “add” of the same Sys.Observable object.

// This will alert my array after new item was added. 
// For complex logic add complex handler to collection changed event

There are more other method you can use with observable arrays: Sys.Observer.remove, Sys.Observer.removeAt, Sys.Observer.addRange, Sys.Observer.insert and Sys.Observer.clear. All of these are documented on Microsoft website, though not very much details are provided. However, you can use this functionality very easy and create advanced logic, without making use of other libraries. Is all about Microsoft Ajax JavaScript library and it is still the base for SharePoint client side functionality (even on SharePoint 2013).


Author: anvlpopescu

Nothing special to say. I'll think about it more and let your know.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s