0 0 0 0


I have a custom binding that depends on two observables: data and selected. Think it as an elaborate table.

In the html it is called as:<div data-bind="myComponent: {}, data: myData, selected: currentSelection"></div>

The ko.bindingHandlers.myComponentupdate function fires when myData and/or currentSelection change. How could I, inside the update function, decide which observable has triggered it? Because if myData changes I have to re-render the component, instead if currentSelection changes I have to only update which element is highlighted.

Is the Knockout : find out which observable triggerred computed the only solution?

Thanks for helping!

Best Answer:

I'm not sure if it's considered "bad practice", but I often bypass the update method by adding my own subscriptions in the init function...

This would allow you to create multiple separated subscriptions that perform the behaviour specific to a change in either data or selected.

I think this method makes you responsible for the disposal of the extra subscriptions, so you might want to do some extra checks for memory leaks..

In the example below you'll see a custom binding that only has an init function. In the init I retrieve two other bindings (left and right in my case, would be data and selected in yours). I define two separate behaviours for when these observables change. At the end of the init function, I call both once.

ko.bindingHandlers.myComponent = {
  init: function(element, valueAccessor, allBindings) {
    var changeLeftColor = function() {
      element.children[0].style.backgroundColor = randomColor();
    var changeRightColor = function() {
      element.children[1].style.backgroundColor = randomColor();
    var leftSub = allBindings.get("left").subscribe(changeLeftColor)
    var rightSub = allBindings.get("right").subscribe(changeRightColor);
    // When knockout disposes the element (for example because 
    // it's in an `if` binding), dispose the subs.
    ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
ko.applyBindings({ left: ko.observable(0), right: ko.observable(0) });
// Utils
function randomColor() {
  return "#" + Array(6).fill().map(function() {
    return "0123456789ABCDEF"[Math.floor(Math.random() * 16)];
div > div {
  display: inline-block;
  width: 40px;
  height: 40px;
  text-align: center;
  line-height: 40px;
<script src=""></script>
<div data-bind="myComponent, left: left, right: right">
  <div data-bind="text: left, click: left.bind(null, left() + 1)"></div>
  <div data-bind="text: right, click: right.bind(null, right() + 1)"></div>

Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs