简体   繁体   中英

custom event in JQuery not triggering

My custom event is very basic, I'm trying to see a console.log message when I click in a input (is a checkbox) inside a div. For any reason my event handler (by using .on) is never fired. Any idea?

// define custom event
$.event.special.selectnetwork = {
  eventType : 'selectnetwork',
  setup: function(data, namespaces) {
   $(this).find('input').bind('change', $.event.special.selectnetwork.handler); 
  },
  teardown: function(namespaces) {

  },
  handler: function(event) {
    event.type = 'selectnetwork';
    console.log('im here'); // I reach this poing
    return $.event.dispatch.apply(this, arguments); // Something wrong?
  }
};

// test the custom event
$('div#mydiv').on('selectnetwork', function(event) {
    console.log('selected'); // never is printed
});

There's a mistake in your .log() that's probably a typo, but it'll stop your script. Other than that, supposedlly custom events need to be bound with .bind() instead of .on()

This doesn't answer your question directly, but because events bubble up to their parents, the following will accomplish what I believe your example intends to do.

$('div#mydiv').on('change', function (e) {
    console.log('selected');
});

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