KnockoutJS:如何将observable传递给自定义绑定?

时间:2014-02-21 15:37:58

标签: javascript knockout.js observable

Javscript:

  var asdasd = {
    test: ko.observableArray([0, 50])
  };

  alert(asdasd.test()); //0,50

  asdasd.test.subscribe(function() {
    return alert("I was changed!!");
  });

  ko.bindingHandlers.rangeslider = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
      var length;

      length = valueAccessor().length; //0 =(
      return alert("Why valueAccessor().length is " + length + " when it wasn't changed? =((");
    }
  };

  ko.applyBindings(asdasd);

HTML:

<div data-bind="rangeslider: test"></div>

问题是valueAccessor()内的init为空,但警告会保留其值。如果我传递rangeslider: test()(unwraping observable),它可以正常工作,但我需要从init更改该可观察值。

那么这个价值在没有通知的情况下会丢失吗?

http://jsfiddle.net/86sAP/3/ - 实例。

1 个答案:

答案 0 :(得分:2)

您必须解包valueAccessor才能获得可观察值:

length = ko.utils.unwrapObservable(valueAccessor()).length; 

这是更新的小提琴:http://jsfiddle.net/86sAP/4/