Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why isn't the checkbox change event triggered when i do it programatically in d3js

Tags:

d3.js

So I have a function that changes the checkbox

somefunction() {
    d3.select("input").property("checked", true);
}

and in another function I have that detects a change in the checkbox like this:

d3.selectAll("input").on("change", change);

The problem I have is when it changes the checkbox without me clicking on it, it will not detect it as a "proper" change. What can I do to make it detect something else changing it as a "proper" change?

like image 314
KNN. T Avatar asked Sep 16 '15 13:09

KNN. T


1 Answers

d3 is using the standard addEventListener in it's on method. The problem you have is that changing the checked property doesn't raise any events for the addEventListener to hear. The proper way would be to just call the handler yourself after setting the proptery:

var myInput = d3.select("input");
myInput.property("checked", true);
myInput.on("change")(); // call it yourself

Full working code:

<!DOCTYPE html>
<html>

  <head>
    <script data-require="[email protected]" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
  </head>

  <body>
    <input type="checkbox" />
    <script>
      
      var checked = false;
      setInterval(function(){
        checked = !checked;
        var myInput = d3.select("input");
        myInput.property("checked", checked);
        myInput.on("change")();
      }, 2000);
      
      
      d3.select("input").on("change", function(d){
        console.log('checkbox changed');
      });

    </script>
  </body>

</html>
like image 55
Mark Avatar answered Oct 01 '22 20:10

Mark