I am using backbone.js here is my scenario
Lets say I have a view called FooView
class FooView extends Backbone.view
initialize:->
$('#manage-foo').bind('click', @render)
render: ->
//whatever I want to render
I want to bind the click on the element #manage-foo to render my view or to call a function of my view FooView but I do not want to loose context in which the function is called, the function render should be called with this
pointing to the FooView rather than the element How do I achieve this. ?
The case that I have is that I create the FooView on pageLoad and I have to show it when a give element is clicked
Thanks
The bind method there is used to bind a method to a context, rather than registering event handlers.
What you should try is:
Thanks Trevor (in the comments) for pointing out you don't need to use the _.bindAll to bind context for events defined in the events object anymore. (Updated the code to reflect that)
Any event handler defined in the events object will automatically be executed in the context of the FooView.
If
#manage-foo
is a child of yourFooView
's@el
then you could use Backbone's event system:If
#manage-foo
isn't within your view's element thenevents
won't work because the event handling is based on jQuery'sdelegate
and thedelegate
call is attached to the view's@el
. In this case you should definerender
with a fat-arrow (=>
) to ensure that it always has the rightthis
when called:You'll also want a
remove
in your view to avoid leaking a reference to your view:Not sure if this answers your question 100% but
_.bindAll(this, 'render');
fixes the loss of context. You can add all of the methods for which you need to do this with, so you can_.bindAll(this, 'render,click');
and add a click method.http://arturadib.com/hello-backbonejs/docs/1.html