-
-
Save ebrunosan/07ddbcc3d9c4a271ab42702c83c16cfc to your computer and use it in GitHub Desktop.
Two-way data binding in pure Javascript
This file contains hidden or 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
| // http://stackoverflow.com/a/16484266/754377 | |
| function DataBind(element, data) { | |
| this.data = data; | |
| this.element = element; | |
| element.value = data; | |
| element.addEventListener("change", this, false); | |
| } | |
| DataBind.prototype.handleEvent = function(event) { | |
| switch (event.type) { | |
| case "change": this.change(this.element.value); | |
| } | |
| }; | |
| DataBind.prototype.change = function(value) { | |
| this.data = value; | |
| this.element.value = value; | |
| }; | |
| var obj = new DataBind(document.getElementById("foo"), "initial"); | |
| // simulate some JS based changes. | |
| var i = 0; | |
| setInterval(function() { | |
| obj.change(obj.element.value + ++i); | |
| }, 3000); |
This file contains hidden or 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
| <pre>Change the value, and the interval will use it.</pre> | |
| <input id="foo"> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment