Search code examples
javascriptjquerybackbone-events

Update Event Handlers when the DOM tree changes


Possible Duplicate:
DOM Mutation event in JQuery or vanilla Javascript

I am using backbone.js with dynamically generated templates and I am using several jQuery UI plugins, which attach to some classes, like slimScroll:

$(function(){
    $('.scroll').slimScroll({
        height: $(window).height();
    });

    $('.stars').changeSelectBoxToRatingStars();
    // ...
});

When I update the DOM tree (by rendering a template, loading new content, ...) and there are new elements added, these bindings need to be refreshed.

There are DOM Tree mutation events, which are now deprecated and not supported by IE (See DOM mutation events replacement). I have also seen .live() in jQuery, which makes it possible to update .click() an similar events, but it can't monitor the DOM for changes. Any suggestions for an efficient, standards-compliant way to monitor DOM tree changes in every browser?


Solution

  • I've finally managed to find a solution myself. As @Šime Vidas suggested in his comment, I am now handling the UI updates directly when needed. This is, when new stuff is rendered (in MainRouter#show)

    class MainRouter extends Backbone.Router
      # [...]
      show: (id) ->
        item = Items.get(id)
    
        # Render item
        @view = new ShowView(model: item)
        $(".content").html(@view.render().el)
    
        # Update scrolling and UI items
        window.updateUI()
    

    and on when the window is resized:

    window.$(window).resize -> window.updateUI()
    

    The window.updateUI() method itself does nothing fancy. It just adds slimScroll scrollbars where necessary and updates some divs, when the window is resized.

    Thank you all for your help!