我创建了一个触发事件的jquery插件:
$.fn.myplugin = function(options) {
this.on("foo.myplugin", options.foo);
this.on("bar.myplugin", options.bar);
};
我想检查foo是否已被用户取消并阻止栏被触发:
// trigger foo
this.trigger("foo.myplugin");
// how do I check if foo was canceled
if( !fooCanceled ) {
this.trigger("bar.myplugin");
}
如何检查foo是否被取消以防止触发条形码?
jQuery UI做了类似的事情,但是当我尝试时它不起作用:
if (this._trigger("search", event) === false) {
return;
}
我尝试了类似的东西:
if( this.trigger("foo.myplugin") === false ) {
return;
}
this.trigger("bar.myplugin");
但是酒吧仍在被触发。
我正在初始化我的插件:
$("#asdf").myplugin({
foo: function(event) {
// cancel the event
event.preventDefault();
},
bar: function(event) {
console.log("should not be triggered");
}
});
答案 0 :(得分:3)
遵循此模式可能会让您完成您所追求的目标。
示例: 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>