Skip to content

Instantly share code, notes, and snippets.

@Colt
Created November 22, 2013 07:31
Show Gist options
  • Save Colt/7596203 to your computer and use it in GitHub Desktop.
Save Colt/7596203 to your computer and use it in GitHub Desktop.
What I have so far for the Zoo Lab. Uses a model, view, and collection to append new animals to the page.
jQuery ->
#Let's make a model guys!!
class Animal extends Backbone.Model
#Let's make a collection of those models
class Animals extends Backbone.Collection
model: Animal
#Main Application View
class ZooView extends Backbone.View
#Set the view's connection to the DOM (el) to our html body
el: $ 'body'
initialize: ->
#we're using underscore's bindAll method
#to basically make sure all methods are run in the context of @ (this) whenever they're invoked
_.bindAll @
@collection = new Animals
#bind the add event to the appendItem() method
#whenever we add to the collection, call the appendAnimal() method
@collection.bind 'add', @appendAnimal
#calls the render method
@render()
#renders the view in @el (the body)
render: ->
#adds empty list for us to append to. Not really needed.
$(@el).append '<ul></ul>'
addAnimal: ->
#grab value of user input
input = $('#animal_input').val()
animal = new Animal
animal.set name: "#{input}"
#add the newly made animal to the collection
@collection.add animal
#trigged when we add to the collection
appendAnimal: (animal) ->
$('ul').append "<li>#{animal.get 'name'}!</li>"
#When you click the add button, trigger addAnimal()
events: 'click #add': 'addAnimal'
#instantiate our main app view
zoo_view = new ZooView
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment