KendoUI MVVM widget custom events.
A custom Kendo widget with external custom events. Allows for kendo's MVVM framework binding with event and value binding.
by cn172
HTML
<script src="http://cdn.kendostatic.com/2013.3.1119/js/kendo.all.min.js"></script>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2013.3.1119/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2013.3.1119/styles/kendo.default.min.css">
This example shows a KendoUI widget creation. The widget is bound to two inputs on the same page and is a theoretical widget that combines an input box with a text box into a single widget. Values changing in one text box will be reflected to the other textbox because they are both bound to the same viewModel field. The first text box has a bound event handler to our custom event called 'buttonclick' that is a custom event defined to fire when the user clicks the button generated by the widget. A div is appended to when the event is fired to show how to capture it in a dependent method and get the value of the widget from the scope.<br /><br />
<div id="modelBound">
Input 1: <input data-role="buttontextbox" data-bind="value: simpleValue, events: { buttonclick: onSomeButtonClick }" /><br />
Input 2: <input data-role="buttontextbox" data-bind="value: simpleValue, events: { buttonclick: onSomeButtonClick" /><br />
Input 3: <input data-role="buttontextbox" data-bind="value: simpleValue2, events: { buttonclick: onSomeButtonClick" /><br />
</div>
<div id="eventsData" />
JavaScript
(function ($) {
var kendo = window.kendo,
ui = kendo.ui,
Widget = ui.Widget,
CHANGE = "change",
BUTTONCLICK = "buttonclick",
BLUR = "blur",
ns = ".kendoButtonTextBox";
var ButtonTextBox = 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));
//Create the DOM elements to build the widget
that._create();
//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: "ButtonTextBox",
value: null,
width: "150px;",
iconclass: "k-i-search",
},
//Convenience method to set the value of the control externally
//Useful for event handlers in dependent methods to be able to
//set the control's value and have it propogate to the MVVM subscribers
set: function (value) {
var that = this;
if (that._old != value) {
//It is different, update the value
that._update(value);
//Capture the new value for future change detection
that._old = value;
// trigger the external change event to notify subscribers
that.trigger(CHANGE);
}
},
//MVVM framework calls 'value' when the viewmodel 'value' binding changes
value: function(value) {
var that = this;
if (value === undefined) {
return that._value;
}
...