有条件地绑定readonly

时间:2014-05-20 16:31:06

标签: javascript knockout.js

这段代码几乎是正确的。我必须单击按钮" make server set"然后进入textarea>进行更改>标签。然后readonly生效。如何修复此代码,以便在单击按钮后readonly立即生效? Fiddle

HTML

<textarea readOnly="true" data-bind="value: text, readOnly: viewModel.text.isServerSet"  rows="5"  cols="20"></textarea> 

<input id="makeServerSet" type="button" value="Make server set" id="makeServerSet" />

的JavaScript

  ko.bindingHandlers.readOnly = {
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        if (value) {
            console.log('element: ' + element);
            console.log('made readonly: ' + value);
            element.setAttribute("readOnly", true); 
        }  else {
            console.log('removed readonly');
            element.removeAttribute("readOnly");
        }  
    }  
}

ko.extenders.isServerSet = function (target, value) {
            console.log('is server set...' + value);
            target.isServerSet = ko.observable(value);
            return target;
        };

var viewModel = {
    text: ko.observable("test").extend({
                isServerSet: false
            }),
    isServerSet: ko.observable('')
}; 

ko.applyBindings(viewModel);

$('#makeServerSet').click(function() {
    viewModel.text.isServerSet = true;
    console.log('made server set');
});

1 个答案:

答案 0 :(得分:1)

在点击处理程序中,使用此

设置isServerSet

viewModel.text.isServerSet(true);(因为它是可观察的)

请参阅updated fiddle