Created
May 14, 2016 19:40
-
-
Save TimboKZ/4ba44857e56838da42e7ae7f5638a41b to your computer and use it in GitHub Desktop.
Two-way Data Binding in JS, read this for more information: http://foxypanda.me/two-way-data-binding
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
<html> | |
<head> | |
<title>Two-way Data Binding</title> | |
</head> | |
<body> | |
<input id="input" type="text"> | |
<button id="change">Set value to "Hello"</button> | |
<span>Value: <strong id="value"></strong></span> | |
<script> | |
// Do nothing if watch() method is already defined | |
if(!Object.prototype.watch) { | |
// Define watch() method for Object | |
Object.defineProperty(Object.prototype, 'watch', { | |
value: function(property, handler) { | |
var value = this[property]; | |
var getter = function() { | |
return value; | |
} | |
// Apart from updating the value, setter also fires the handler | |
var setter = function(newValue) { | |
value = handler.call(this, property, value, newValue); | |
return value; | |
} | |
// Deleting the property, do nothing if the value is a constant | |
if(delete this[property]) { | |
// Adding the property again, with out getter() and setter() | |
Object.defineProperty(this, property, { | |
configurable: true, | |
get: getter, | |
set: setter | |
}); | |
} | |
} | |
}); | |
} | |
// Initialise input variable | |
var input = { | |
value: '' | |
} | |
// Setting up elements | |
var inputEl = document.getElementById('input'); | |
var changeEl = document.getElementById('change'); | |
var valueEl = document.getElementById('value'); | |
// Setup watcher to update #input and #value | |
input.watch('value', function(property, oldValue, newValue) { | |
inputEl.value = newValue; | |
valueEl.textContent = newValue; | |
return newValue; | |
}); | |
// Updating the value as an example | |
input.value = 'Testing'; | |
// Setup click event for the change button | |
changeEl.addEventListener('click', function(event) { | |
input.value = 'Hello'; | |
}); | |
// Update the variable on input change | |
inputEl.addEventListener('keyup', function(event) { | |
input.value = inputEl.value; | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment