How can I stop event propagation with Backbone.js?

前端 未结 5 1086
面向向阳花
面向向阳花 2021-01-31 16:01

Using a Backbone.js View, say I want to include the following events:

    events: {
        \'click a\': \'link\', 
        \'click\': \'openPanel\' 
    }


        
相关标签:
5条回答
  • 2021-01-31 16:14

    Each of your event handlers will be passed an event object when it's triggered. Inside your handler, you need to leverage jQuery's event.stopPropagation() method. For example:

    link: function(event) {  
      //do some stuff here
      event.stopPropagation();
    }
    
    0 讨论(0)
  • 2021-01-31 16:20

    Two other methods that might work for you:

    1

    events: {
        'click a': 'link', 
        'click *:not(a, a *)': 'openPanel' 
    }
    

    Then openPanel will not capture click events on any <a> or child of an <a> (in case you have an icon in your <a> tag).

    2

    At the top of the openPanel method, make sure the event target wasn't an <a>:

    openPanel: function(event) {
        // Don't open the panel if the event target (the element that was
        // clicked) is an <a> or any element within an <a>
        if (event && event.target && $(event.target).is('a, a *')) return;
    
        // otherwise it's safe to open the panel as usual
    }
    

    Note that both of these methods still allow the openPanel function to be called from elsewhere (from a parent view or another function on this view, for example). Just don't pass an event argument and it'll be fine. You also don't have to do anything special in your link function -- just handle the click event and move on. Although you'll probably still want to call event.preventDefault().

    0 讨论(0)
  • 2021-01-31 16:31

    I've been using e.stopImmediatePropagation(); in order to keep the event from propagating. I wish there was a shorter way to do this. I would like return false; but that is due to my familiarity with jQuery

    0 讨论(0)
  • 2021-01-31 16:31

    Return "false" in your "link" function.

    0 讨论(0)
  • 2021-01-31 16:37

    The JQuery preventDefault method would also be a good option.

        window.LocationViewLI = Backbone.View.extend({
            tagName: "li",
            template: _.template('<a href="/locations/<%= id %>"><%= name %></a>'),
    
            events: {
                "click a": "handleClick"
            },      
            handleClick: function(event) {
                event.preventDefault();
                console.log("LocationViewLI handleClick", this.model.escape("name") );
                // debugger;
            },
            ...
    
    0 讨论(0)
提交回复
热议问题