jQuery事件触发器 - 可取消事件

4

我创建了一个 jQuery 插件,它触发了一个事件:

$.fn.myplugin = function(options) {
    this.on("foo.myplugin", options.foo);
    this.on("bar.myplugin", options.bar);
};

我想检查用户是否取消了foo,并防止触发bar:
// trigger foo
this.trigger("foo.myplugin");

// how do I check if foo was canceled
if( !fooCanceled ) {
    this.trigger("bar.myplugin");
}

如何检查foo是否已取消,以防止触发bar?

jQuery UI做了类似的事情,但我尝试时它没有成功:

if (this._trigger("search", event) === false) {
    return;
}

我尝试过类似于这样的操作:

if( this.trigger("foo.myplugin") === false ) {
    return;
}

this.trigger("bar.myplugin");

但是bar仍然被触发了。

我是这样初始化我的插件的:

$("#asdf").myplugin({
    foo: function(event) {
        // cancel the event
        event.preventDefault();
    },

    bar: function(event) {
        console.log("should not be triggered");
    }
});

你尝试过this._trigger('foo.myplugin') === false吗? - Explosion Pills
我曾经以为 _trigger 是 jQuery UI 的一部分,但我并没有使用它。我只是拿他们的代码作为一个例子。 - Dismissile
你能定义一下“被用户取消”的含义吗? - rae1
@rae1n 确定。假设我在对话框等上有一个close和closing事件。Closing事件会给用户一个机会来阻止关闭事件发生,比如弹出一个确认框询问他们是否确定要关闭。如果他们选择不关闭,它只会触发closing处理器而非close处理器。这就是我所说的取消事件。 - Dismissile
1个回答

4
遵循这个模式可能会让你实现你想要的目标。 示例: http://jsfiddle.net/VzzLf/3/ JS
//Plugin structure from : http://docs.jquery.com/Plugins/Authoring
(function( $ ){

  var methods = {
     init : function( options ) {

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

           ele.on('click.myPlugin', function(e){

               //Hold a reference to the event
               var event = $.Event("closing")

               //Trigger it on the element
               ele.trigger(event); 

               //Check to see if it was disabled
               if(!event.isDefaultPrevented()){
                   ele.trigger('close');
               }

           }); 

       });

     }
  };

  $.fn.myPlugin = function( method ) {

    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.myPlugin' );
    }    

  };

})( jQuery );

  $(function(){
      $('#myPlugin')
          .myPlugin()
          .on('closing', function(){
            alert('closing');      
          })
          .on('close', function(){
            alert('close fired');      
          });   
      $('#myPluginDisabled')
          .myPlugin()
          .on('closing', function(e){
              alert('Disable close'); 
              e.preventDefault(); 
          })
          .on('close', function(e){
              alert('Will never get here'); 
          });      
  }); 
​

HTML

<div id='myPlugin'>Click me I'm enabled</div>

<div id='myPluginDisabled'>Click me I'm disabled</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接