Skip to content

zecar/Object-Property-Watch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 

Repository files navigation

JavaScript Watch Object property changes

I've started with Eligrey's Gist and modified it a bit.

What it does

It monitors javascript objects and fires a callback once some property changes. You can use it to trigger functions when some property in some object changes

General syntax

someObject.watch(callback, propsToWatch); // start watching
someObject.unwatch(propsToUnwatch); // stop watching 

Callback

function someName(newVal, oldVal, key){
	// do whatever
}

Props to watch

You can pass a string

	someObject.watch(callback, 'name');

You can pass an array

	someObject.watch(callback, ['name', 'age']);

You can pass nothing, in which case it will monitor all properties of the object

	someObject.watch(callback);

Props to unwatch

Same as above

Usage

var dog = {
	breed: 'pug',
	name: 'Doug',
	lastFed: 60
}
dog.watch(function(newVal, oldVal, key){
	if(newVal <= 0){
		console.log("I want food again");
		clearInterval(window.dogFeddInterval);
	}
	else{
		console.log("I'm not hungry yet, I'm going to play with my toys.")
	}
}, 'lastFed');

window.dogFeddInterval = setInterval(function(){
	dog.lastFed -= 10;
}, 10000);

About

Simple library to watch object changes in javascript

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published