Created
November 24, 2018 15:00
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use https://raw.githack.com/ to embed this gist with proper mimetype into my codepen.io pens as https://gist.githack.com/matths/1ea82b24326692d327b7c265a9dee8fa/raw/5c88c31d0ec3e73941164a2dfa51d47a6df58822/Binding.js