Skip to content

Instantly share code, notes, and snippets.

@mattmccray
Created October 14, 2010 08:44
Show Gist options
  • Save mattmccray/625893 to your computer and use it in GitHub Desktop.
Save mattmccray/625893 to your computer and use it in GitHub Desktop.
Use Backbone.js classes as native CoffeeScript classes
# Backbone CoffeeScript Helpers by M@ McCray.
# Source: http://gist.github.com/625893
#
# Use Backbone classes as native CoffeeScript classes:
#
# class TaskController extends Events
#
# class TaskView extends View
# tagName: 'li'
# @SRC: '<div class="icon">!</div><div class="name"><%= name %></div>'
#
# constructor: ->
# super
# @template= _.template(TaskView.SRC)
# @render() if @model?
#
# render: ->
# $(@el).html @template( @model.toJSON() )
#
# Etc...
#
class Events
_.extend(Events::, Backbone.Events)
this.Events = Events
class Model
constructor: ->
Backbone.Model.apply(this, arguments)
_.extend(Model::, Backbone.Model.prototype)
this.Model = Model
class Collection
constructor: ->
Backbone.Collection.apply(this, arguments)
_.extend(Collection::, Backbone.Collection.prototype)
this.Collection = Collection
class View
constructor: ->
Backbone.View.apply(this, arguments)
_.extend(View::, Backbone.View.prototype)
this.View = View
@SlexAxton
Copy link

Saw this and was going to use it, but then saw this:

http://github.com/documentcloud/backbone/commit/1d57168c8f436f1f9b20a5fa7f13495610931b22

Figured I'd let people know that this is no longer necessary.

@jwhitley
Copy link

Actually, it is still necessary in the case of Backbone.Events, which is a plain 'ol JS object (as of Backbone 0.9.1):

class Wombat extends Backbone.Events
  # props, methods, etc...

The approach above works fine, however:

class Wombat
  _.extend(Wombat::, Backbone.Events)
  # props, methods, etc...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment