Search code examples
javascriptbackbone.jsmarionette

Change Backbone view template on window resize


I want to change the template of a view on window resize, to make it responsive. This works fine when reloading the page, but I cannot update the template dynamically. As per the documents I have used this to set the template on page load:

getTemplate: function() {
    if ($(window).width() > 1024){
        this.desktopLayout = true;
        return '#MenuView';
    } else {
        this.desktopLayout = false;
        return '#MenuViewTablet';
    }
},

This works fine when you navigate to the page, but when the function is called on 'resize', it doesn't update the template.


Solution

  • In your ItemView:

    onShow : function () {
      $(window).on("resize.myNamespace", _.throttle(_.bind(this.render, this), 50));
    },
    onClose : function () {
      $(window).off("resize.myNamespace");
    }
    
    • Listen for window resize event
    • Throttle render calls because resize event is fired very rapidly
    • Bind this reference for render call
    • Re-render view on resize; (render will call getTemplate again)
    • Use onShow event so the binding only happens after the view has been inserted into the DOM
    • Cleanup listener in onClose event to prevent errors later on, namespace to prevent collisions with other code.