Created
April 4, 2012 11:01
-
-
Save kambara/2300371 to your computer and use it in GitHub Desktop.
template class definition using CoffeeScript and Backbone
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#= require another_class | |
#= require_tree ./models | |
#= require_tree ./views | |
window.my_app ?= {} | |
##### | |
# Model | |
##### | |
class my_app.MyModel extends Backbone.Model | |
defaults: | |
text: '' | |
# url: -> "/[collection.url]/[id]" | |
# urlRoot: -> "/api" | |
# initialize: (attrs) -> | |
parse: (response) -> | |
{} | |
validate: (attrs) -> | |
# if attrs.end < attrs.start | |
# return "can't end before it starts" | |
##### | |
# Collection | |
##### | |
class my_app.MyCollection extends Backbone.Collection | |
model: MyModel | |
# initialize: ([models], [options]) | |
# url: -> "/api" | |
# comparator: (m) -> m.get('order') | |
##### | |
# View | |
##### | |
class my_app.MyView extends Backbone.View | |
# tagName: 'div' | |
# className: '' | |
# id: '' | |
# attributes: {} | |
template: _.template $("#template").html() | |
events: | |
# "dblclick" : "open", | |
# "click .icon.doc" : "select", | |
## Several special options will be attached directly to the view: | |
## model, collection, el, id, className, tagName and attributes | |
initialize: (options) -> | |
# @model.on 'change', () -> doSomething() | |
@render() | |
render: -> | |
$(@el).html template @model.toJSON() | |
@ | |
# select: () -> @model.set {selected: true} | |
# open: () -> window.open @model.get("viewer_url") | |
# save: () -> @model.save {text: 'hello'} | |
###### | |
# Template in haml | |
###### | |
%script#template{:type => "text/template"} | |
%div | |
Hello | |
<%= name %> | |
##### | |
# Router | |
##### | |
class my_app.MyRouter extends Backbone.Router | |
# initialize: ([options]) -> | |
routes: | |
'': 'index' | |
index: -> | |
new my_app.MyView({ | |
model: new my_app.MyCollection({ | |
text: 'Hello' | |
}) | |
}) | |
##### | |
# main | |
##### | |
my_app.main = () -> | |
$ -> | |
new MyRouter() | |
Backbone.history.start() | |
## Other Examples | |
# - http://documentcloud.github.com/backbone/docs/todos.html | |
# - http://documentcloud.github.com/backbone/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment