Last Updated: February 25, 2016
·
3.12K
· tarmann

Extend your Backbone View with some helpful methods

I've been working with Backbone.js for a couple of months now and after creating loads of different Views you realize that you are writing the same piece of functionality over and over again.

To avoid that you can just extend your Backbone View with those methods and call them later. Here are some of the ones that I use:

Render only a piece of the template

Backbone.View.prototype.renderElement = function (selector, data) {
    var html = $('<div>').html(this.template(_.extend({}, this.model.toJSON(), data)));
    this.$el.find(selector).replaceWith($(selector, html));
    return this;
}

Scroll to an element

Backbone.View.prototype.scrollToElement = function (selector, time, verticalOffset) {
    var time = typeof(time) != 'undefined' ? time : 200,
        verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0,
        element = $(selector),
        offset = element.offset(),
        offsetTop = offset.top + verticalOffset;

    $('html, body').animate({ scrollTop: offsetTop }, time);
}

Display a loading overlay on top of the view

Backbone.View.prototype.renderLoading = function(){
    var loadingHtml = '<div class="loading">'
    + '<div class="loading-overlay"></div>'
    + '<div class="loading-icon"></div>'
    + '</div>';

    this.$el.append(loadingHtml);
}

And this is an example on how to use them:

var PageView = Backbone.View.extend({

    initialize: function(options){
        this.model.on({
            'request': this.renderLoading,
            'sync': this.updateElement
        }, this);
    },

    updateElement: function(){
        this.renderElement('.element');
        this.scrollToElement('.element');
    }

    // some methods to do stuff with the model
});

2 Responses
Add your response

I always have this one defined in my base backbone views to avoid memory leak.

Reference: http://stackoverflow.com/a/11534056

destroy_view: function() {

//COMPLETELY UNBIND THE VIEW
this.undelegateEvents();

this.$el.removeData().unbind(); 

//Remove view from DOM
this.remove();  
Backbone.View.prototype.remove.call(this);

}
over 1 year ago ·

That's a good one @vraa! Thanks!

over 1 year ago ·