CoryG
CoryG

Reputation: 2581

Stop jQuery event propagation for specific event handler

I'm attempting to stop event propagation only for a specific event handler, while allowing others on the same event to propagate, here is an example:

function Control(parent) {
    this.Parent = $(parent);
    this.Parent.append('<div class="test"></div>');
    this.Test = $('.test', this.Parent).last();
    this.Test.bind('mousedown', this, Control_All);
    this.Test.bind('mousedown', this, Control_Top);
}
function Control_All(event) {
    //this should bubble up through both c1 and c2
}
function Control_Top(event) {
    //this should stop at c2
}
Control.prototype.constructor = Control;
Control.prototype.All = Control_All;
Control.prototype.Top = Control_Top;

var c1 = new Control('body');
var c2 = new Control(c1.Test);

In the example above c1.Test and c2.Test are the same size. I am attempting to make a mousedown event call these three events (I'm aware that the OO methodology isn't maintained and state is kept via event.data, but am using OO notation for simplicity, in my actual use case the All and Single delegates are bound variable orders and only in some instances, so the order in which they are bound cannot be controlled):

c1.All
c2.All
c2.Single

I've attempted event.preventDefault(), event.stopPropagation(), event.stopImmediatePropagation() and return(false) at the end of Control_Top, but none work to do as described above.

Edit: Here is a JSFiddle Link to assist anyone interested in helping with it.

Edit again: Solved using a global and an extra bind to body.mousedown, here it is if anyone needs it, would welcome a solution that doesn't use a global or an extra binding.

Upvotes: 0

Views: 1705

Answers (1)

Kevin B
Kevin B

Reputation: 95031

Just confirm that the event target is equal to the element you bound the event to.

http://jsfiddle.net/cvmEz/2/

function Control(parent,name) {
    this.Parent = $(parent);
    this.Parent.append('<div class="test" data-name="' + name + '"></div>');
    this.Test = $('.test', this.Parent).last();
    this.Test.bind('mousedown', this, Control_All);
    this.Test.bind('mousedown', this, Control_Top);
}
function Control_All(event) {
  if ( event.target == this) {
    console.log(this.getAttribute('data-name') + '.All');
  }
}
function Control_Top(event) {
  if ( event.target == this) {
    console.log(this.getAttribute('data-name') + '.Top');
  }
}
Control.prototype.constructor = Control;
Control.prototype.All = Control_All;
Control.prototype.Top = Control_Top;

var c1 = new Control('body', 'c1');
var c2 = new Control(c1.Test, 'c2');

console.log('--------');

Upvotes: 3

Related Questions