I’m having some difficulty with backbone js. Currently, I have a rails app that is giving information to backbone via json. It appears that this is all function correctly because when I navigate to the URL, the json data is displayed. I’m having difficulty when I am using the fetch method. Below is my code:
jQuery ->
class Event extends Backbone.Model
url: '/events/get_last'
defaults:
name: 'This isnt from the server'
date_of: '2012-03-01'
max_attendees: '300'
class EventList extends Backbone.Collection
url: '/events/get_events'
model: Event
class EventView extends Backbone.View
el: $ 'body'
model: Event
initialize: (options) ->
_.bindAll @
@event = new Event
@event.fetch()
@render()
render: ->
$(@el).append "<span>#{@event.get 'name'}"
class EventRouter extends Backbone.Router
routes :
'' : 'home'
'dashboard' : 'render_data_view'
'default' : 'default_view'
home: ->
console.log "home"
render_data_view: ->
event_view = new EventView
default_view: ->
console.log 'the default view was hit'
initialize: ->
Backbone.history.start(pushState: true)
event_router = new EventRouter
Your EventView should bind to its model’s
"change"event so thatfetchwill trigger things automatically:So your view should look more like this:
A few notes:
bindAllwith CoffeeScript, use the fat arrow (=>) instead.modelproperty on views should be set per-instance to a single model (hence the@event->@modelname change). Collections get theirmodelproperty set in the class definition and the@modelfor a collection should be a model class."change"event on the model means that your view will be notified (i.e.@renderwill be called) whenever anyone changes the model, this event behavior is sort of the whole point of Backbone so you should use it, the per-fetchsuccess and error handlers are more for error handling and reporting success to the user.<span>elements.@$elso you might as well use that instead of$(@el).el: 'body'instead ofel: $ 'body'and leave the jQueryification to Backbone.bindinstead ofon.@$elso$(@el)might be needed instead.