I’ve got problems using bindAll. The error I get is func is undefined. Any thoughts on what I’m doing wrong?
I’ve tried both
bindAll(fails with the above error) and- individual
binds (don’t work)
window.test = Backbone.View.extend({
collection: null
initialize: ->
console.log('initialize()')
console.log(this)
# _.bindAll(this, ["render", "foo"])
_.bind(this.render, this) # these don't throw errors, but binding won't work
_.bind(this.foo, this)
@collection = new Backbone.Collection()
@collection.bind "add", @render
@collection.bind "add", @foo
@render()
foo: ->
# won't be bound to the view when called from the collection
console.log("foo()")
console.log(this)
console.log(this.collection) # undefined (since this is the collection, not the view)
render: ->
console.log("render()")
console.log(this)
return this
})
testInstance = new window.test();
# using _.bind instead of bindAll we get past this point, however this won't be the view
testInstance.collection.add({})
You are using CoffeeScript, you don’t need underscore’s bind. CoffeeScript has it built in. Just use “fat arrows”
Search for “fat arrow” here: http://jashkenas.github.com/coffee-script/
However, with regards to
_.bindAll, you don’t need to provide the method names as an array. You can do either_.bindAll(this)or_.bindAll(this, 'render', 'foo')(method names are var args, not an explicit list). See if that helps.