.scroll() jquery is not working within knockout custom binding handler?

856 Views Asked by At

I use Durandal (requireJS + knockoutJS) with jQuery

jquery 1.10.2 + knockoutjs 2.3.0 + requirejs

even a simple code won't work

 $('#table1').scroll(function(){
      alert('');
 });

even fadeOut(); fadeIn() are not working

but EACH function is working properly

$('.items').each(function(){ 
     $(this).css("display","none"); 
});

any guess? thanks

2

There are 2 best solutions below

0
On

It may be that the problem is you're trying to scroll a table itself. Scrolling a div works for me. You'll get an alert when you try to move the scrollbar.

ko.bindingHandlers.scrollBinder = {
  init: function(element) {
    $(element).scroll(function() {
      alert("Scroll!");
    });
  }
};

var model = function() {
  var self = {};
  self.visibleStatus = ko.observable(true);

  return self;
};

ko.applyBindings(new model());
.scrolly {
  overflow-y: scroll;
  max-height: 300px;
  width: 300px;
}
.bigblock {
  height: 800px;
  width: 300px;
  background-color: #cfc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="scrolly" data-bind="scrollBinder:true">
  <table>
    <tbody>
      <td class="bigblock"></td>
    </tbody>
  </table>
</div>

0
On

If your DOM is being loaded after that JQuery event handler is wired up, it won't wire up at all (e.g. if the 'table1' table is added after you've added that event handler because it's loaded via AJAX or similar). Instead, you'll need to do some kind of event delegation. The easiest way to do this is to attach the event to something that will exist (document is an obvious one), and filter the event handler. e.g.

$(document).on('scroll','#table1', function(e) {...});

That way, because document actually handles the event, it doesn't matter that 'table1' is added later as that filter is evaluated at the time the event handler is fired.