I’m trying to use backbone with coffeescript instead javascript:
TodoItem = Backbone.Model.extend(
toggleStatus: ->
if @.get 'status' is "incomplete"
@.set 'status': 'complete'
else
@.set 'status': 'incomplete'
@.save()
)
todoItem = new TodoItem(
description: 'I play the guitar'
status: 'incomplete'
id: 1
)
TodoView = Backbone.View.extend(
tagName: 'div'
id: "box"
className: 'red-box'
events:
"click h3": "alertStatus"
'change input': 'toggleStatus'
template:
_.template "<h3> <input type=checkbox #{ print "checked" if status is "complete"} /> <%= description %></h3>"
initialize: ->
@.model.on 'change', @.render, @
@.model.on 'destroy', @.remove, @
toggleStatus: ->
@.model.toggleStatus()
alertStatus: ->
alert('Hey you clicked the h3!')
remove: ->
@.$el.remove()
render: ->
@.$el.html @.template(@.model.toJSON())
)
todoView = new TodoView({model: todoItem})
todoView.render()
console.log todoView.el
If I try in console:
todoItem.set({description: 'asdfadfasdfa'});
I get:
ReferenceError: todoItem is not defined
Also, I can’t see inside of my body the div:
<div id="box" class="red-box">
<h3>
<input type="checkbox" undefined>
"I play the guitar"
</h3>
</div>
But I can see this div in my console fine.
Where is it the error?
Thank you!
One of the nice things about CoffeeScript is that you can use
@fooinstead of@.foo. A little less to write and a little nicer to read.You don’t have to use Backbone’s
.extend(), because CoffeeScript has classes that work in a completely compatible manner:todoItemisn’t defined because CoffeeScript will wrap all of your code in an “immediately executed function expression”, which prevents leaking variables to the global scope (this is a good thing). From the docs:If you want to inspect local variables, set a breakpoint in Chrome’s debugger or Firebug.
I’m worried about this code:
What is
print? Where have you defined that? For that matter, where isstatus? Do you mean@status?Finally, the reason you’re not seeing the
divis that you never added it to the DOM..render()renders the element…but it doesn’t automatically insert it on the page for you. You have to do that yourself: