开发者

JQuery stop event bubbling from method call

开发者 https://www.devze.com 2023-04-06 16:54 出处:网络
I am trying to get my head around the jquery plugin structure and wrote the following HTML code which forms the start of a slideshow:

I am trying to get my head around the jquery plugin structure and wrote the following HTML code which forms the start of a slideshow:

<div id="bubble" style="width: 200px; height: 200px; background: #ccc;"></div>
<script type="text/javascript">
jQuery.noConflict();
(function($) {
    $(function() {
        $(document).ready(function() {
            $("#bubble").bubble();
    });
});
})(jQuery);
</script>

This is linked to the following jquery plugin code:

(function($){
var i = 0;

var methods = {
    mouseup: function(e){
        $(this).bubble('next');
        e.stopPropagation();
    },
    mousedown: function(e){
        $(this).bubble('next');
        e.stopPropagation();
    },
    next: function(){
        console.log(i++);
    }
};

$.fn.bubble = function(method){
    $(this).bind("mouseup", methods.mouseup)
          .bind("mousedown", methods.mousedown);

    if ( methods[method] ) {
    return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } 
开发者_StackOverflow};

})(jQuery);

I'm not sure why but clicking the bubble box calls multiple iterations of the next: method. Is there a way to limit the number of calls to the next: method?


You are binding mousedown and mouseup to the next function, this will send two next functions per click, I don't think you are meaning to do that.

In order to fix it, remove one of the binds, or just bind click.


Maybe you should use stopImmediatePropagation() so that you just log twice (because you call next() twice):

(function($){
var i = 0;

var methods = {
    mouseup: function(e){
        $(this).bubble('next');
        e.stopImmediatePropagation();
    },
    mousedown: function(e){
        $(this).bubble('next');
        e.stopImmediatePropagation();
    },
    next: function(){
        console.log(i++);
    }
};

$.fn.bubble = function(method){
    $(this).bind("mouseup", methods.mouseup)
          .bind("mousedown", methods.mousedown);

    if ( methods[method] ) {
    return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    }
};

})(jQuery);

fiddle: http://jsfiddle.net/k3FhM/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号