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");
    }
});
4

1 回答 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>​
于 2012-12-18T20:24:20.763 回答