Knockout绑定包装器,输入更改不会触发可观察的订阅

时间:2018-01-08 08:18:09

标签: javascript knockout.js

我正在尝试围绕KO textInput绑定编写一个简单的包装器。输入填充初始值" abc"但是当我在输入中键入任何新值时,相应的observable不会更新。我在这里错过了什么?我对KO很新。

ko.bindingHandlers.myBind = {
init: function(element, valueAccessor, allBindings) {
  var test= ko.observable("abc");
  test.subscribe(function(newVal){console.log(newVal);});
  ko.bindingHandlers.textInput.init(element, test, allBindings);     
}
};
ko.applyBindings()

// html
<input data-bind="myBind" />

1 个答案:

答案 0 :(得分:1)

valueAccessor参数必须是函数才能返回observable:

&#13;
&#13;
ko.bindingHandlers.myBind = {
  init: function(element, valueAccessor, allBindings) {
    var test= ko.observable("abc");
    test.subscribe(function(newVal){console.log(newVal);});
    var newValueAccessor = function(){ return test; };
    ko.bindingHandlers.textInput.init(element, newValueAccessor, allBindings);     
  }
};

ko.applyBindings();
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<input data-bind="myBind" />
&#13;
&#13;
&#13;