Skip to content

Instantly share code, notes, and snippets.

@shahzadns
Last active December 22, 2017 09:18
Show Gist options
  • Save shahzadns/30caeb931487adcf98fb4e31e64926f7 to your computer and use it in GitHub Desktop.
Save shahzadns/30caeb931487adcf98fb4e31e64926f7 to your computer and use it in GitHub Desktop.
Watcher demonstration on angular 1.x scope properties - using built-in set, get of objects.
/**
* Created on: Dec 22 2017
* Created by: Shahzad Nawaz
* Derived from different sources, Stakoverflow, Blogs, experience.
*/
console.clear(); //--snippets - clear prev run log
/* rocking Scope class for $watch only */
function Scope() {
this.__watchers = {};
}
Scope.prototype.$watch = function (propName, handler) {
var _self = this;
// write the existing value
this.__watchers[propName] = this[propName];
// setup the watcher listener against the given property
Object.defineProperty(this, propName, {
set: function(newVal) {
var oldValue = this.__watchers[propName];
this.__watchers[propName] = newVal;
handler.call(this, newVal, oldValue);
},
get: function() {
return this.__watchers[propName];
}
});
// setup the listener deregister.
return function() {
var value = _self[propName];
// delete the setter (the value itself gets deleted too)
delete _self[propName];
delete _self.__watchers[propName];
// add back the value
_self[propName] = value;
}
}
// controller scope - angular auto instantiates it
var scope = new Scope();
/* play with the scope instance object*/
scope.foo = 'before watch value';
var destroyListener = scope.$watch('foo', function(newVal, oldValue) {
console.log('foo changed. new value: ', newVal, ' | oldValue: ', oldValue);
});
// changes noew started beign monitored
scope.foo = 'first change';
scope.foo = 'second change';
scope.foo = 'third change';
// destroy listeners
destroyListener();
console.log('watcher destroyed for the property: foo');
// no longer monitored
scope.foo = 'fourth change';
scope.foo = 'fifth change';
console.log('--');
console.log('no delete keyword watcher support yet - God knows how ng team does that. > _ <');
console.log('Cheers ! ^_^');
@shahzadns
Copy link
Author

logs

foo changed. new value:  first change  | oldValue:  before watch value
foo changed. new value:  second change  | oldValue:  first change
foo changed. new value:  third change  | oldValue:  second change
watcher destroyed for the property:  foo
--
no delete keyword watcher support yet - God knows how ng team does that. > _ <
Cheers ! ^_^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment