Skip to content

Instantly share code, notes, and snippets.

@matths
Created November 24, 2018 15:00
Show Gist options
  • Save matths/1ea82b24326692d327b7c265a9dee8fa to your computer and use it in GitHub Desktop.
Save matths/1ea82b24326692d327b7c265a9dee8fa to your computer and use it in GitHub Desktop.
simple two way binding with vanilla js as explained by Blaize Stewart (@theonemule) at https://www.wintellect.com/data-binding-pure-javascript/
// inspired by @theonemule (Blaize Stewart) via https://www.wintellect.com/data-binding-pure-javascript/
window.Binding = (function () {
var bindingStore = {};
function Binding(prop, obj) {
if (!obj) {
obj = bindingStore;
bindingStore[prop] = undefined;
}
var self = this;
this.bindings = [];
this.value = obj[prop];
this.valueGetter = function () {
return self.value;
};
this.valueSetter = function (val) {
for (var i = 0; i < self.bindings.length; i++) {
var binding = self.bindings[i];
if (binding.func) {
if (binding.scope) {
val = binding.func.apply(binding.scope, [val]);
} else {
val = binding.func(val);
}
}
if (binding.element && binding.attribute) {
binding.element[binding.attribute] = val;
}
if (binding.element && binding.style) {
binding.element.style[binding.style] = val + 'px';
}
}
self.value = val;
};
this.addElement = function (element, attribute, event) {
var binding = {
element: element,
attribute: attribute
};
if (event) {
element.addEventListener(event, function (event) {
self.valueSetter(element[attribute]);
})
binding.event = event;
}
this.bindings.push(binding);
element[attribute] = self.value;
return self;
};
this.addFunction = function (func, scope) {
var binding = {
func: func,
scope: scope
};
this.bindings.push(binding);
if (scope) {
func.apply(scope, [self.value]);
} else {
func(self.value);
}
return self;
};
this.addStyle = function (element, style) {
var binding = {
element: element,
style: style
};
this.bindings.push(binding);
element.style[style] = self.value + 'px';
return self;
}
Object.defineProperty(obj, prop, {
get: this.valueGetter,
set: this.valueSetter
});
obj[prop] = this.value;
}
Binding.store = bindingStore;
return Binding;
})();
@matths
Copy link
Author

matths commented Nov 24, 2018

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