Skip to content

Instantly share code, notes, and snippets.

@nsisodiya
Created September 18, 2013 09:36
Show Gist options
  • Save nsisodiya/6606812 to your computer and use it in GitHub Desktop.
Save nsisodiya/6606812 to your computer and use it in GitHub Desktop.
Two Way Data binding using Rivet and Watch.js + Concept of Model Class !!
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);
}
};
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);
});
https://rawgithub.com/mikeric/rivets/master/dist/rivets.min.js
https://rawgithub.com/melanke/Watch.JS/master/src/watch.js
https://rawgithub.com/nsisodiya/watchjs-adapter-for-rivetsjs/master/watchjs-adapter-for-rivetsjs.js
See demo @ http://jsfiddle.net/nsisodiya/y3gDP/3/
<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>
var PersonClass = function (name, task) {
this.name = name;
this.job = {
task: task
}
this.__theSecrectLinkForClass__ = PersonClass;//This is imp, so that Rivets Handler know proper context !
};
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment