Created observable

This commit is contained in:
Borys Levytskyi
2015-04-04 16:22:52 +03:00
parent 097f38746b
commit dd2175f04a
2 changed files with 52 additions and 45 deletions

View File

@@ -1,51 +1,7 @@
(function(){ (function(){
var bindr = {}; var bindr = {};
bindr.model = function(definition){ bindr.bindElement = function(element, model, propertyName) {
var model = new bindr.Model();
for(var property in definition){
if(!definition.hasOwnProperty(property)){
continue;
}
Object.defineProperty(model, property, {
get:bindr.Model.createGetter(property),
set:bindr.Model.createSetter(property)
});
model[property] = definition[property];
}
return model;
};
bindr.Model = function() {
this.executionHandlers = [];
};
bindr.Model.createGetter = function (propertyName){
return function(){
return this["_" + propertyName];
}
};
bindr.Model.createSetter = function(propertyName){
return function(value){
this["_" + propertyName] = value;
this.notifyPropertyChanged(propertyName, value);
}
};
bindr.Model.prototype.observe = function (handler){
this.executionHandlers.push(handler);
};
bindr.Model.prototype.notifyPropertyChanged = function(propertyName, value){
this.executionHandlers.forEach(function(h){
h(propertyName, value);
});
};
bindr.bindElement = function(element, model, propertyName) {
if(element.bindr != null) { if(element.bindr != null) {
return; return;
} }

51
core/observable.js Normal file
View File

@@ -0,0 +1,51 @@
(function(){
var observable = {};
observable.create = function(definition){
var obj = new bindr.ObservableObject();
for(var property in definition){
if(!definition.hasOwnProperty(property)){
continue;
}
Object.defineProperty(obj, property, {
get:bindr.ObservableObject.createGetter(property),
set:bindr.ObservableObject.createSetter(property)
});
obj[property] = definition[property];
}
return obj;
};
observable.ObservableObject = function() {
this.executionHandlers = [];
};
observable.ObservableObject.createGetter = function (propertyName){
return function(){
return this["_" + propertyName];
}
};
observable.ObservableObject.createSetter = function(propertyName){
return function(value){
this["_" + propertyName] = value;
this.notifyPropertyChanged(propertyName, value);
}
};
observable.ObservableObject.prototype.observe = function (handler){
var handlers = this.executionHandlers;
var index = handlers.push(handler);
return function () { handlers.splice(1, index); }
};
observable.ObservableObject.prototype.notifyPropertyChanged = function(propertyName, value){
this.executionHandlers.forEach(function(h){
h(propertyName, value);
});
};
window.observable = observable;
});