Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Xamlizer - a way to implement INotifyPropertyChang* in JavaScript!
var xamlizer = (function() {
'use strict';
var __hasOwn = Object.prototype.hasOwnProperty;
var propSkeleton = function() {
this.enumerable = true;
this.configurable = true;
//this.writable = true;
};
return function(o) {
var propertyChanging, propertyChanged, prop, value,
locals = {},
_propertyChanged = [],
_propertyChanging = [];
propertyChanging = function(name) {
for(var i = 0, il = _propertyChanging.length; i < il; i++) {
_propertyChanging[i](o, name);
}
};
propertyChanged = function(name) {
for(var i = 0, il = _propertyChanged.length; i < il; i++) {
_propertyChanged[i](o, name);
}
};
for(var name in o) {
if (!__hasOwn.call(o, name)) {
continue;
};
(function (name) {
prop = new propSkeleton();
prop.get = function() {
return locals[name];
};
prop.set = function(val) {
if(val !== locals[name]) {
propertyChanging(name);
locals[name] = val;
propertyChanged(name);
}
}
value = o[name];
Object.defineProperty(o, name, prop);
o[name] = value;
})(name);
}
o.addPropertyChanged = function(fn) {
_propertyChanged.push(fn);
};
o.addPropertyChanging = function(fn) {
_propertyChanging.push(fn);
};
o.removePropertyChanged = function(fn) {
var index = _propertyChanged.indexOf(fn);
if(index >= 0) {
_propertyChanged = _propertyChanged.slice(0, index).concat(_propertyChanged.slice(index + 1, _propertyChanged.length));
}
};
o.removePropertyChanging = function(fn) {
var index = _propertyChanging.indexOf(fn);
if(index >= 0) {
_propertyChanging = _propertyChanging.slice(0, index).concat(_propertyChanging.slice(index + 1, _propertyChanging.length));
}
};
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.