Backbone.js and jquery binding click event to a vi

2019-09-06 22:08发布

问题:

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

回答1:

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



回答2:

If #manage-foo is a child of your FooView's @el then you could use Backbone's event system:

class FooView extends Backbone.View
  events:
    'click #manage-foo': 'render'
  #...

If #manage-foo isn't within your view's element then events won't work because the event handling is based on jQuery's delegate and the delegate call is attached to the view's @el. In this case you should define render with a fat-arrow (=>) to ensure that it always has the right this when called:

render: =>
  #...

You'll also want a remove in your view to avoid leaking a reference to your view:

remove: ->
  $('#manage-foo').off('click', @render)
  Backbone.View::remove.apply(@)


回答3:

The bind method there is used to bind a method to a context, rather than registering event handlers.

What you should try is:

class FooView extends Backbone.View
  events:
    "click #manage-foo": "render"  
     # this registers @render as the event handler for clicking on the #manage-foo element in the view

  render: ->
    # your rendering code

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.