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:
- Is there a reason I’m overlooking as to why there are so few examples of backbone methods factored out into common libraries?
- Is there a standard/agreed upon location in backbone projects for shared code?
- Any backbone classes and/or common plugins to help store common methods?
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?
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.
Then, instead of creating
new Backbone.View()s, I’d createnew DestroyableView()s.DestroyableViewcould have other common functions, or you could create several different parent definitions and use_.extend()to apply them all to a single object.