delegateEvents in backbone.js

后端 未结 2 1254
囚心锁ツ
囚心锁ツ 2021-01-30 17:43

Can anyone please explain me what delegateEvents in backbone.js does? The documentation did not help me to understand.

My exact use case is:

I have a main view X

相关标签:
2条回答
  • 2021-01-30 17:56

    delegateEvents takes the events: { ... } declaration for your view instance, and binds the specified events to the specified DOM elements, with the specified callback methods to handle the events.

    So, a DOM tree that looks like this after being rendered:

    <div> 
      <a href="#" id="foo">foo</a>
    </div>
    

    And a view defined like this:

    
    Backbone.View.extend({
      events: {
        "click .foo": "fooClicked"
      },
    
      fooClicked: function(e){
        // handle the click, here
      },
    
      render: function(){
        // render the specified HTML, here
      }
    });
    

    will properly handle clicking the "foo" link, so that you can respond to the click in your code.

    The breakdown of the events declaration is: "eventname selector": "callback" where "eventname" is any DOM event, such as "click". "selector" is any valid jQuery selector, which is run against your view's el for the DOM element to bind the event to. "callback" is the name of the method on this view to call, when the event for that DOM element fires.

    hope that helps

    0 讨论(0)
  • 2021-01-30 18:08

    Essentially, when you call .remove() it is a proxy to the jQuery remove function, which removes the element from the DOM, as well as all associated events from the event hash that were bound to the element.

    Backbone's View element still contains the .el, but upon re-inserting in the DOM, the jQuery element has lost all of it's bound listeners.

    There are a few solutions:

    1. Completely destroy the view element, including unbinding all model/controller events with the new destroy method (currently only in the github, it will be added in the next release of Backbone) and create a new view when coming back (rather than just caching and re-rendering) - my preferred method

    2. Create a method (or extend remove) to use jQuery's detatch which apparently does the same as remove without losing the event bindings - haven't done it but seems like it would work

    3. Call .delegateEvents() in every render - what you're currently doing now

    Hope this helps.

    0 讨论(0)
提交回复
热议问题