简体   繁体   中英

How to manually trigger a backbone click event without actually clicking

I have a backbone event handlers set up like this:

events : {
          "click .filter-options-container" : "filterOptionContainerClick",
    },

For one of these .filter-options-container elements, there is a scenario in which I want to trigger the "filterOptionContainerClick" function without actually clicking. The problem is that function needs access to event.currentTarget - so I can't just call the function - I have to simulate that click event. How do I do this? Here's that function:

filterOptionContainerClick: function(e){

      if (this.filtersEnabled){
        $(e.currentTarget).addClass('active');
      } else {
        return;
      }

    },

why not just check if e is an event or an element. then you could use it however you want.

events: {
    'click .filter-options-container': 'filerOptionContainerClick',
},
//....
filterOptionContainerClick: function( obj ) {
    if( !this.filtersEnabled || !obj ) {
        return;
    }

    if( obj.currentTarget ) {
        $( obj.currentTarget ).addClass( 'active' );
    } else if( $( obj ) && $( obj ).hasClass( 'filter-options-container' ) ) {
        $( obj ).addClass( 'active' );
    }
 }

In other words, you could then just call filterOptionContainerClick manually. Something like:

 //.....
     this.filterOptionContainerClick( $( '.filter-options-container' ) );
 //....

If you need to give each contain a unique identifier, you can either do this with an id attribute on the element, or just use a custom data-whatever attribute (ie, <div class="filter-options-container" data-identifier='some unique id'>...</div> )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM