Skip to content

Instantly share code, notes, and snippets.

@nhajratw
Created December 12, 2011 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nhajratw/1468963 to your computer and use it in GitHub Desktop.
Save nhajratw/1468963 to your computer and use it in GitHub Desktop.
Trying to get basic CoffeeScript/Backbone working
There are 2 main problems with the code below:
1) It appears that fetch is getting called twice somehow
2) The fetched JSON is not parsing into the OfferClass objects.
I have a server that returns the following JSON at /offerClasses
[ {"id":1,"name":"Introductory"}, {"id":2,"name":"Loyalty"} ]
Coffee file
===========
window.app =
models: {}
views: {}
class app.models.OfferClass extends Backbone.Model
class app.models.OfferClasses extends Backbone.Collection
model: app.models.OfferClass
url: "/offerClasses"
class app.views.OfferClassesView extends Backbone.View
initialize: ->
@model.bind "reset", @render
render: =>
@model.each @addToDropDown
@
addToDropDown: (offerClass) =>
$(@el).append($("<option></option>").
attr("value",offerClass.get("id")).
text(offerClass.get("name")))
head.ready ->
model = new app.models.OfferClasses()
view = new app.views.OfferClassesView model: model, el: $('#offer-class-list')
model.fetch()
HTML file
=========
<html>
<head>
<title>Offer Entry</title>
<script type="text/javascript" language="JavaScript"
src="http://cdnjs.cloudflare.com/ajax/libs/headjs/0.96/head.min.js">
</script>
</head>
<body>
<div id="offer-type-section">
Offer Class: <select id="offer-class-list" />
</div>
</body>
<script>
head.js(
"http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js",
"http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.2.2/underscore-min.js",
"http://cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js",
"http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.5.3/backbone-min.js",
"../lib/all_code.js"
);
</script>
</html>
@BrianGenisio
Copy link

So, I'd do the following:

  1. Take @fetch out of the Collection.initialize
  2. Take @offerClasses = new OfferClasses out of the View.initialize
  3. In your Doc.ready, construct the collection, pass it in to the view with model: collection.

As for your parsing error, it is difficult to say. Pass an error and success function in to find out what is going on. Any exceptions being thrown?

@BrianGenisio
Copy link

I forked the CS and hacked it a bit. I haven't tested it, I made it more idiomatic: https://gist.github.com/1472549

@nhajratw
Copy link
Author

Updated with working code! Thanks Brian.

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