Friday, December 19, 2014

Sending data to CanJS component

Ideally, components should be independent, but sometimes it is needed to send data or call function on component from outside. It is possible to do by using observable like can.Map and listen to events on it from component like:

<script type="text/javascript">
  var observable = new can.Map({val:0});

  $(function() {
    can.Component.extend({
      tag: "my-tag",
      events: {
        "{observable} val": function(param, param2, newval){
          alert(newval);
        }
      }
    });
    $('#myTagDiv').html(can.view.mustache('<my-tag/>'));
  });
</script>



<div id="myTagDiv"></div>
<input type="button" value="Call observable" onclick="observable.attr('val', observable.val+1);">


This way all components will receive observable change event either they are sent from itself, other component or directly from JavaScript.