Search code examples
javascriptjqueryobserver-pattern

Efficiently tracking and updating an array of DOM elements with Javascript / jQuery?


Inside of a module I'm writing (its kind of a slider / timeline interface component) I've got a method that updates the controls which are a set of clickable elemetns along the bottom that are updated on click and when the user scrolls.

I'm doing the following to attach classes to the items up until the active one. While the approach I'm using works, its feels very inefficient as I'm looping over a set of DOM elements each time.

     updateTimeLine : function(pos, cb) {

        var p = pos;
        var timeline = $('.timer').toArray();
        if (p > 15)
            p = 15;

        $.each(timeline, function(index,value) {
            var that = $(this);
            if (index >= p) {
                if (that.children('span').hasClass('active'))
                    that.children('span').removeClass('active');
            } else {
                that.children('span').addClass('active');
            }
        });

        if (cb && typeof(cb) === "function") {
            cb();
        }

        return this;
    },

Is there a better way to do this? If so, how?

Is this a good use case for something like the observer pattern? which I don't fully get, having not spent any time with it yet, so if it is, I'd really like to know how to apply this pattern properly.


Solution

  • Observer patterns notify subscribed objects by looping through and invoking listeners on each subscriber when a relevant change occurs. Because of that, you'd probably end up using $.each anyways. I think what you have is equally efficient.

    If you feel bad about iterating over the dom each time, consider this: there exists no such algorithm that can update each dom element without iterating through them. Caching the DOM array theoretically would improve performance, but my money says the browser's already doing that. Try it yourself on this jsperf...