Two way binding using Rivets.js + WatchJS
Two way binding using Rivets.js + WatchJS
HTML
<script src="https://rawgithub.com/melanke/Watch.JS/master/src/watch.js"></script>
<script src="https://rawgithub.com/mikeric/rivets/v0.5.12/dist/rivets.min.js"></script>
<script src="https://rawgithub.com/nsisodiya/watchjs-adapter-for-rivetsjs/master/watchjs-adapter-for-rivetsjs.js"></script>
<div id="module">
<button data-on-click="scope:change">Change Model Data(1)</button>
<button id="changeType2">Change Model Data(2)</button>
<button data-on-click="scope:showData">Show Model Data</button>
<h3><span data-text="scope.name"></span> is <span data-text="scope.job.task"></span> </h3>
<input data-input="scope.name">
<input data-input="scope.job.task">
<p>Please type in input box and press Enter, These fields are 2 way binded, Changing the Model data automatically refelected to UI and changing UI data will be refelected in Model</p>
</div>
JavaScript
// These Demo work on rivet 0.5.12, Let me know if you able to make it work on lastet branch !
//This use https://rawgithub.com/nsisodiya/watchjs-adapter-for-rivetsjs/master/watchjs-adapter-for-rivetsjs.js
//Visit https://github.com/nsisodiya/watchjs-adapter-for-rivetsjs/
/////////// Modify the Soruce Code for Rivets //////////
rivets.config.handler = function (context, ev, binding) {
console.log(binding.model.constructor);
if (binding.model instanceof binding.model.__theSecrectLinkForClass__) {
return this.call(binding.model, ev, context); //Event Target !!
} else {
return this.call(context, ev, binding.view.models);
}
};
////////////////// binder /////////////
rivets.binders.input = {
publishes: true,
routine: rivets.binders.value.routine,
bind: function (el) {
el.addEventListener('input', this.publish);
},
unbind: function (el) {
el.removeEventListener('input', this.publish);
}
};
////////// Main Code Start HEre -- Modal Class /////////////////
var PersonClass = function (name, task) {
this.name = name;
this.job = {
task: task
}
this.__theSecrectLinkForClass__ = PersonClass;
};
PersonClass.prototype = {
change: function (Event, TargetEle) {
this.name = "Chetan";
this.job.task = "Playing";
},
showData: function (Event, TargetEle) {
alert(JSON.stringify(this));
},
setFromController: function (name, task) {
this.name = name;
this.job.task = task;
}
}
//////////// Main Coding Starts Here //////////////
var scope = new PersonClass("Narendra", "Engineer");
document.querySelector("#changeType2").onclick = function () {
scope.setFromController("Deepak", "Running");
};
rivets.bind(document.querySelector("#module"), {
scope: scope
});
watch(scope, function () {
console.log(arguments);
});