2

I'm using a third-party lazyload plugin: http://www.appelsiini.net/projects/lazyload

In its source, it has the following:

if (0 === settings.event.indexOf("scroll")) {
    $container.on(settings.event, function (event) {
        return update();
    });
}

This applies a 'scroll' event to the parent element. There's no logic in the plugin for unbinding the event. This sucks because sometimes I will add 100s lazy elements and then remove and re-add others without replacing the container. This causes tons of events to stack up!

I'm considering modifying the plugin to read something like:

if (0 === settings.event.indexOf("scroll")) {
    //  .on('scroll.item_12')
    $container.on(settings.event + settings.namespace, function (event) {
        return update();
    });

    //  http://stackoverflow.com/questions/2200494/jquery-trigger-event-when-an-element-is-removed-from-the-dom
    $(this).on('remove', function() {
        $container.off(settings.event + settings.namespace);
    });
}

Is this the correct way of handling such a scenario? When working with BackboneJS I have access to: http://backbonejs.org/#Events-listenTo, but I'm not certain that a similiar function exists in just jQuery/Javascript

Sean Anderson
  • 27,963
  • 30
  • 126
  • 237
  • I've namespaced events in jQuery like this: `scroll.left`/`scroll.right`, etc. – Jared Farrish Feb 02 '14 at 16:51
  • 1
    No, but you can implement this method in your own. And this is quite easy - https://github.com/jashkenas/backbone/blob/master/backbone.js#L221, https://github.com/jashkenas/backbone/blob/master/backbone.js#L157 – Vitalii Petrychuk Feb 02 '14 at 18:36
  • Even backbone using jquery `event.namespace` to handle DOM events. No there is nothing like `listenTo` in jquery, but you could implement, using event.namespace is better and easier! (Even with implementing listenTo for jquery you must use a unique id for namespacing with `event.namespace`) – KiT O Feb 03 '14 at 06:52

1 Answers1

0

in jQuery you only have two methods; on and off. Or simply call remove() on each element that you're trying to get rid of.

$(document).off(elementName)
Muhaimin
  • 1,643
  • 2
  • 24
  • 48