简体   繁体   中英

KnockoutJS: How pass observable to custom binding?

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>

Problem is that valueAccessor() inside init is empty, but alert stays that it has values. It works fine if I am passing rangeslider: test() (unwraping observable), but I need change value of that observable from init .

So where this value lost without notifying about it change?

http://jsfiddle.net/86sAP/3/ - live example.

You have to unwrap valueAccessor to get observable's value:

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

Here is updated fiddle: http://jsfiddle.net/86sAP/4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM