Skip to content

Instantly share code, notes, and snippets.

@namlet
Created February 9, 2011 23:37
Show Gist options
  • Save namlet/819586 to your computer and use it in GitHub Desktop.
Save namlet/819586 to your computer and use it in GitHub Desktop.
Maintain selection coordinates using a closure. This example using jQuery.
var boxCoord = function(endCoord) {
var coord = endCoord;
return function(anotherCoord) {
return [anotherCoord, coord];
}
}
$('body').mousedown(function(e){
var thate = e;
$(this).mouseup(function(e){
var box = boxCoord([e.pageX,e.pageY])([thate.pageX,thate.pageY]);
console.log(box);
});
});
@webdevwilson
Copy link

$('body').mousedown(function(e) { 
  $(this).mouseup(function(f) { 
    console.log([[e.pageX, e.pageY], [f.pageX, f.pageY]]); 
  }); 
});

@namlet
Copy link
Author

namlet commented Feb 10, 2011

That's far more concise. Was trying out some patterns from Crockford's JavaScript book, the good parts.

@webdevwilson
Copy link

ha ha, I just noticed we are adding the mouseup event every time they mousedown. So after n mousedowns, the mouseup will be called n times.

@namlet
Copy link
Author

namlet commented Feb 10, 2011

True, to fix...

$('body').mousedown(function(e) {
  $(this).bind('mouseup.box',function(f) {
    console.log([[e.pageX, e.pageY], [f.pageX, f.pageY]]);
    $(this).unbind('mouseup.box');
  });
});

@webdevwilson
Copy link

deadHorse.beat();

(function() {
  var d = {};
  $('body').bind({
    mousedown: function(e) { d.start = [e.pageX, e.pageY]; },
    mouseup: function(e) { d.end = [e.pageX, e.pageY]; console.log(d); }
  });
})();

@azizshamim
Copy link

@webdevwilson - won't arbitrarily binding both events to a dom object mean that you could - say - have a mouseup event that occurs before the mousedown event? wouldn't that mean that the console.log(d) writes out an incomplete d object?

@namlet: what's the mouseup.box for?

@webdevwilson
Copy link

@azizshamim - I guess. But isn't it equally possible that the late bound mouseup could be missed completely? At least in my model the coordinates will still be captured.

@namelet - I was wondering about the mouseup.box as well.

@azizshamim
Copy link

@webdevwilson - i have no idea. i'm a javascript newbie. i asked namlet for a "how to do x" this is the result...

@webdevwilson
Copy link

@azizshamim - ha ha, no one does. Perhaps the browser is slow firing the mousedown event and for some reason the mouseup is fired before the mousedown. Surely that violates a spec or something. Of course, no browser implementation would ever dare to violate a spec. Would they? Welcome to javascript. :)

@namlet
Copy link
Author

namlet commented Feb 11, 2011

mouseup.box is namespacing. That way when you unbind it, it only removes the handlers specifically registered with that namespace, mouseup.box.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment