Question

JQuery has great support for custom events - .bind("foo", function(e).... However what if the mechanic of triggering the event is not ready yet and has to be constructed only on those elements that have the event bound on?

For example I want a scrollin event that gets fired when an element is scrolled into a viewport. To do this, I would onscroll have to check all the elements and trigger scrollin on those that were outside the viewport and now are inside. This is not acceptable.

There are some tricks to speed it up. For example one of the plugins for this checks all the elements in "private" $.cache and does the checking only on those that have scrollin event bound.

But that's also ugly. What I need is an additional callback for the binding of the event (additional to the callback for handling) that would take care of the scroll management, that is to put the element(s) into some elementsCheckOnScrol cache array.

I'm looking for something like:

$.delegateBind("scrollin", function(jqSelection) { ... });
element.bind("scrollin", function(e) {..}); //Calls ^ after internal bind management

Edit: This would be nice api!

$.bind("bind", function(onWhat) { ... }) 

:-)

Was it helpful?

Solution 2

I found an $.event.special API, but I don't know "how much" public it is. It is not in the docs and has been changed at least once before. http://benalman.com/news/2010/03/jquery-special-events/

OTHER TIPS

If I'm not misunderstanding you, you could patch the bind method like this:

(function($) {
    var oldBind = $.fn.bind;

    $.fn.bind = function(name) { 
        if(name === "scrollin") {
             delegateFunction(this);
        }

        oldBind.apply(this, arguments);
    };
})(jQuery);

What it does is checking whether a scrollin is being bound, and if so, calls your delegate function. After that it simply calls the original bind function which does all jQuery things like it does regularly.

After having added this code, you could use it like this: http://jsfiddle.net/pimvdb/g4k2G/.

function delegateFunction(selection) {
    alert(selection.length);
}

$('a').bind('scrollin', function() {});

Note that this does not support object literals being passed to .bind (only (name, func)), but you could implement that as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top