Skip to content

Instantly share code, notes, and snippets.

@jotto
Created March 8, 2012 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jotto/2003071 to your computer and use it in GitHub Desktop.
Save jotto/2003071 to your computer and use it in GitHub Desktop.
# Example Backbone.js app in CoffeeScript
# compile on each file save using the coffee bin
# coffee -b -c -w app.coffee
# BACKBONE.JS MODEL
class Blog extends Backbone.Model
sync: -> "noop"
url: ->
return "blogs" if this.isNew()
return "blogs/#{this.id}"
# BACKBONE.JS COLLECTION
class BlogCollection extends Backbone.Collection
model: Blog
# overriding the fetch method. normally fetch() grabs a resultset from a REST server
fetch: ->
this.reset([
{id: 1, name: "blog post 1", body: "some text", created_at_int: 1},
{id: 2, name: "blog post 2", body: "some text", created_at_int: 2}
])
comparator: (model) ->
# keeps this in descending order
model.get('created_at_int') * -1
url: ->
return "blogs"
# BACKBONE VIEW
class IndividualBlogView extends Backbone.View
tagName: "li"
render: ->
this.$el.append("<h2>#{this.model.get('name')}</h2><strong>#{this.model.get('body')}</strong>")
return this
# ANOTHER BACKBONE VIEW
class ListOfBlogsView extends Backbone.View
initialize: ->
_.bindAll(this, 'add')
this.collection.on "reset", => this.reset_collection()
tagName: "ul"
add: (_model) ->
childView = new IndividualBlogView(model: (_model))
@childViews.push(childView)
this.$el.append(childView.render().$el)
reset_collection: ->
_(@childViews).each (cv) -> cv.off(); cv.remove()
@childViews = []
_(@collection.models).each(this.add)
render: ->
# reset_collection will build and append the views for
# the collection in the case where the collection was populated
# before this render() method was called (going forward, the "reset" event
# will appropriately trigger the reset_collection method)
this.reset_collection()
# insert the view into the DOM
$("div#content").append(this.$el)
# BACKBONE ROUTER
class Router extends Backbone.Router
initialize: (options) ->
routes:
"": "index"
index: ->
window.collection = new BlogCollection()
window.collection.fetch()
window._view = new ListOfBlogsView(collection: window.collection)
_view.render()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="./underscore-min.js"></script>
<script src="./backbone-min.js"></script>
<script src="./app.js"></script>
<div id="content"></div>
<script>
window.router = new Router()
Backbone.history.start()
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment