Simple MVVM KendoUI custom Widget Part 2 - Value binding
A simple custom KendoUI widget that is MVVM aware.
HTML
<script src="http://cdn.kendostatic.com/2013.3.1119/js/kendo.all.min.js"></script>
This example shows a simpl KendoUI MVVM aware widget creation. <br /><br />
<div id="modelBound">
Input 1: <input data-role="simplewidget" data-bind="value: simpleValue" /><br />
Input 2: <input data-role="simplewidget" data-bind="value: normalValue" /><br />
</div>
JavaScript
(function ($) {
var kendo = window.kendo,
ui = kendo.ui,
Widget = ui.Widget,
CHANGE = "change",
BLUR = "blur",
ns = ".kendoSimpleWidget";
var SimpleWidget = Widget.extend({
// Kendo calls this method when a new widget is created
init: function (element, options) {
var that = this;
Widget.fn.init.call(this, element, options);
//Create a blur event handler.
element = that.element
.on(BLUR + ns, $.proxy(that._blur, that));
//Set the value from the options.value setting, if it was called with a static value
if (options.value) {
that.value(options.value);
}
},
//List of all options supported and default values
options: {
name: "SimpleWidget",
value: null,
width: "150"
},
//MVVM framework calls 'value' when the viewmodel 'value' binding changes
value: function(value) {
var that = this;
if (value === undefined) {
return that._value;
}
that._update(value);
that._old = that._value;
},
//Export the events the control can fire
events: [CHANGE],
// this function creates each of the UI elements and appends them to the element
//blur event handler - primary UI change detection entry point
_blur: function () {
var that = this;
that._change(that.element.val());
},
//Update the internals of 'value'
_update: function (value) {
var that = this;
that._value = value;
that.element.val(value);
},
_change: function (value) {
var that = this;
//Determine if the value is different than it was before
if (that._old != value) {
...