The following script renders required field background color of Kendo UI combobox control. Although this script works perfectly fine, I find it hard to understand it.

From what I can tell, it starts off with attaching custom property or method so called _input to Kendo ui combobox object and assign into new variable _originalFunction but rather than using this variable it's using this chained object again in the next line which I don't really get and assign returned result into this from an anonymous function that listens to an event.

In general, I don't really get what is happening inside this function and what the returned value would be.

Can someone please explain in a way I can understand?

(function ($) {
    var _originalFunction = kendo.ui.ComboBox.fn._input;
    kendo.ui.ComboBox.fn._input = function (e) {
        var result = _originalFunction.call(this, e);
        if (this.input) {
            this.input.addClass('required');
        }
        return result;
    }
})(jQuery);
有帮助吗?

解决方案

what is happening here is, the _input from kendo's ComboBox library is enhanced to add a class required to the input element.

If you use _originalFunction instead of kendo.ui.ComboBox.fn._input in the assignment line then, you are only changing the value of local variable _originalFunction, not the function referred by kendo

(function ($) {
    var _originalFunction = kendo.ui.ComboBox.fn._input; // store the original function to a variable so that it can be called later
    kendo.ui.ComboBox.fn._input = function (e) { // overwrite the _input  function
        var result = _originalFunction.call(this, e); // call the original function to apply default functionality
        if (this.input) { // additional functionality is added here
            this.input.addClass('required');
        }
        return result;
    }
})(jQuery);

The original method accepts a single parameter, so when we call the original method, we need to use the same context and parameters as it was expecting, that is the reason for the line _originalFunction.call(this, e). But it should be better written as _originalFunction.apply(this, arguments) as it is safe against any future change in that method signature

其他提示

This is modifying the behavior of Kendo's ComboBox _input method. It saves the original value of this function in the variable _originalFunction, then gives the function a new definition. The new definition calls the original method, saves its result, adds the required class to the input field of the combobox, and then returns that saved result.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top