PlankTon
PlankTon

Reputation: 12605

How to organise common code

Just getting started with backbone.js, and one of the things I've noticed is that many of my models, collections and views share some very similar methods. I'd like to refactor them & call them from an extracted location (/lib?). I went searching for documentation and/or examples, and was surprised by how little I found (specifically, none). So, a few questions:

Any ideas appreciated - thanks in advance.

(EDIT) Example added:

Take this code from a view. (Admittedly it's too short be actually worth refactoring, but its simplicity makes it a concise example)

  destroy: () ->
    @model.destroy()
    @remove()
    return false

Suppose I wanted to refactor it into:

  destroy: () ->
    restful_destroy_method(this)

which then called:

 restful_destroy_method: (view) ->
    view.model.destroy()
    view.remove()
    return false

from a common library. Any reason why nobody else seems to do this?

Upvotes: 2

Views: 220

Answers (2)

Rob Hruska
Rob Hruska

Reputation: 120316

It depends on the situation, and what your common code is.

In the case of your example, what I might do would be to create a more specific View to extend from.

Apologies for the straight JavaScript, I'm not as fluent in CoffeeScript to use it in an answer.

DestroyableView = Backbone.View.extend({
    destroy: function () {
        this.model.destroy();
        this.remove();
        return false;
    }
});

Then, instead of creating new Backbone.View()s, I'd create new DestroyableView()s. DestroyableView could have other common functions, or you could create several different parent definitions and use _.extend() to apply them all to a single object.

Upvotes: 5

Atinux
Atinux

Reputation: 1703

You can use a "Basic View" which own the generic methods :

// Create a Basic View which have all generic methods
var BasicView = Backbone.View.extend({
    restful_destroy_method: function () {
        this.model.destroy();
        this.remove();
        return false
    }
});

// Create a view which herits the methods of BasicView
var ExampleView = BasicView.extend({
    destroy: function () {
        this.restful_destroy_method();
    }
});

You can show an example on jsFiddle here : http://jsfiddle.net/Atinux/YDMNg/

Upvotes: 1

Related Questions