I’m using experimenting with .extend() to set up my views and initialise them with. I’ve found it’s convenient to assign config variables to view objects nested deep within a hierarchy.
My problem is that my Views lose their this context. This becomes the ctor object which I asume is the constructor. How can I fix this?
My coffeescript is below. The first class would be nested deep within a tree, the second is at the top level where the application boots up:
# This is a child somewhere deep within a tree of views.
class View extends Backbone.View
initialize: ->
console.log @ # returns object ctor
MyView = View.extend({
initialize: ->
# do config stuff then init prototype
App.Views.MyView.prototype.initialize()
})
view = new MyView
Two things:
First, and not as importantly, you can use
instead of
View.extend. CoffeeScript classes and Backbone classes are interoperable.Second—and this is the important part—instead of
you should simply use the CoffeeScript keyword
That effectively does the same thing, but also ensures that the function is called in the correct context. Bonus: It also passes in all of your function arguments for you.
If you’re curious,
superhere compiles into(where
__super__is a reference to the superclass that’s set by both CoffeeScript’sextends). Read aboutapplyat MDN.