sg-observable-array

0.0.2 • Public • Published

TOC

sg-observable-array

Will allow you to hook in to the arrays methods to modify the array in any way you want.

var tags = [ 1, 2, 3 ];
/**
 * Make the array `Observable`
 */
ObservableArray( tags );
/**
 * Say we want to ensure the array only contains numbers when values are pushed
 */
tags.on( 'push', function ( _value ) {
	/**
	 * The original array methods are accessible with the same name prefixed with '__'
	 */
	return tags.__push( parseInt( _value ) );
} );
tags.push( '4' );
tags.should.eql( [ 1, 2, 3, 4 ] );

They are still Arrays.

var tags = [ 1, 2, 3 ];
/**
 * Make the array `Observable`
 */
ObservableArray( tags );
tags.should.be.an.Array;

If an Array method is not being listened to, then the normal array behavior will apply.

var tags = [ 1, 2, 3 ];
/**
 * Make the array `Observable`
 */
ObservableArray( tags );
/**
 * We have not defined an `on` method for 'pop' so Array.prototype.pop will apply
 */
tags.pop();
tags.should.eql( [ 1, 2 ] );

By defining a listener, it's possible to prevent the array from changing.

var tags = [ 1, 2, 3 ];
/**
 * Make the array `Observable`
 */
ObservableArray( tags );
tags.on( 'unshift', function () {
	return 'chicken';
} );
tags.unshift().should.equal( 'chicken' );
tags.should.eql( [ 1, 2, 3 ] );

Readme

Keywords

none

Package Sidebar

Install

npm i sg-observable-array

Weekly Downloads

6

Version

0.0.2

License

MIT

Last publish

Collaborators

  • davidtsuji