jQuery自定义事件

时间:2009-10-14 13:45:22

标签: jquery custom-event

为什么不触发这个?

$('#nav').bind('app:event', function (event, status) {
  console.log([event, status]);
});

这是:

$(document).bind('app:event', function (event, status) {
  console.log([event, status]);
});

使用以下方式触发事件:

$(this).trigger('app:event', [options]);

来自插件。

这是整个街区:

/* App.js */
$(function ($) {

  // UI Panels
  $('#panels').panels({
    controls: '#nav a'
  });

  $('#nav').bind('app:event', function (event, status) {
    console.log([event, status]);
  });

});

/**
 * Plugin dir
 */
(function($) {
  // Interface
  $.fn.panels = function (options) {
    var settings = {}, current;

    if (options) {
      $.extend(settings, options);
    }

    // Setup
    $('.panel', this).hide();
    $('.panel:first', this).slideDown('slow');

    return this.each(function () {
      var self = $(this);

      $(settings.controls).click(function () {
        // Get reference
        current = this.href.substring(this.href.indexOf('#') + 1);

        // Hide all
        $('.panel', self).hide();
        // Show current
        $('#'+ current)
          .publish({            
            'panelReady': current
          })
          .slideDown();

        return false;
      });
    });
  };

  // Publish event
  $.fn.publish = function (options) {    
    var settings = {
      origin: this      
    };

    if (options) {
      $.extend(settings, options);
    }

    return this.each(function () {
      $(this).trigger('app:event', [options]);
    });
  };

}(jQuery));

我正在尝试实现类似于suplish / subscribe / observer之类的解决方案,其中#id可以订阅事件

2 个答案:

答案 0 :(得分:0)

尝试放置$(document).ready()

$(document).ready(function() {
    $('#nav').bind('app:event', function (event, status) {
          console.log([event, status]);
    });
});

答案 1 :(得分:0)

很难用这么少的代码说。当你试图触发它时,你确定$(this)是指$(“#nav”)吗?