kendo-labs / knockout-kendo

A project to create a robust set of Knockout.js bindings for the Kendo UI widgets.
http://kendo-labs.github.com/knockout-kendo/
273 stars 144 forks source link

ReadOnly binding #88

Open Rakesh-gene opened 11 years ago

Rakesh-gene commented 11 years ago

Hi Guys, It's not an issue, just a query. Can we have readOnly binding?, because kendo is supporting readOnly property and it will be of great help If there is a way for achieving the same.

Regards, Rakesh

hidegh commented 9 years ago

+1

I use the following code to make KO bind to read only.

Unfortunately this is not enough, cause setting the control's read only attribute in DOM does not equal to calling $("my item selector").data("kendoControlTypeName").readonly(bool);

The reason why disabled is not enough: disabled control values does not get posted back! So we REALLY NEED read-only.

$(function () {

    // NOTE: https://github.com/knockout/knockout/issues/1100
    // Support for readOnly binding!
    ko.bindingHandlers.readOnly = {
        update: function (element, valueAccessor) {
            var value = ko.utils.unwrapObservable(valueAccessor());
            if (value) {
                element.setAttribute("readOnly", true);
                // ev. set disabled style - $(element).addClass("disabled");
            } else {
                element.removeAttribute("readOnly");
                // ev. set disabled style - $(element).removeClass("disabled");
            }
        }
    }

    // NOTE: http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html
    //
    // Usage #1:
    // <div data-bind="stopBinding: true">
    //
    // Usage #2:
    // <div>
    //  <h2 data-bind="text: header"></h2>
    //  <!-- ko stopBinding: true -->
    //  <div id="profile">
    //      <input data-bind="value: first" />
    //      <input data-bind="value: last" />
    //  </div>
    //  <!-- /ko -->
    // </div>

    ko.bindingHandlers.stopBinding = {
        init: function () {
            return { controlsDescendantBindings: true };
        }
    };

    ko.virtualElements.allowedBindings.stopBinding = true;
});