1

Is it possible to bind events on body element inside a view?

For example this doesn't work

Backbone.View.extend({
  el : "#some element here",
  events : {
    "mouseup body" : "onMouseUp"
  }
});

Thanks in advance

chchrist
  • 18,854
  • 11
  • 48
  • 82

2 Answers2

1

I think is not possible.

Backbone.View.events uses internally this.$el.delegate which internally uses CSS selector which looks like doesn't support upwards selection.

You can instead add a position: absolute div into your el DOM element and make it transparent and fullscreen it. And then capture events from there.

Community
  • 1
  • 1
fguillen
  • 36,125
  • 23
  • 149
  • 210
1

Well I think I found a working solution!

In the initialize function I do

$('body').bind('mouseup', this.onMouseUp);

And it works like charm! :)

EDIT

Actually there is a big problem with that! The this is bind on the body and not on the view. So I have a parameter "pressed" and when I access it with this.pressed it tries to find it in the body....

EDIT

The solution I found to the problem above is to pass in the bind parameters a reference to this like:

$('body').bind('mouseup',{thisView : this}, this.onMouseUp);

And now it works like charm :P

chchrist
  • 18,854
  • 11
  • 48
  • 82
  • still I think my answer match your question _"Is it possible ..."_ ;) – fguillen Apr 19 '12 at 10:06
  • Well you're right it is not possible to have a "mouseup body" : "method here" in a view with different el – chchrist Apr 19 '12 at 10:24
  • @fguillen Can you see my edited answer. How should I fix this? – chchrist Apr 19 '12 at 10:32
  • the eternal _JS context dilema_ :).. you can fix this in different approachs. 1) [the one you have found](http://forum.jquery.com/topic/setting-a-context-in-fn-bind), 2) [using jQuery.proxy()](http://api.jquery.com/jQuery.proxy), 3) [using Underscore.bindAll](http://stackoverflow.com/a/6396224/316700), 4) (sure there are more) – fguillen Apr 19 '12 at 10:52
  • cool, I understand proxy but how can I use the bindAll? What is the most elegant way? – chchrist Apr 19 '12 at 10:57
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/10271/discussion-between-chchrist-and-fguillen) – chchrist Apr 19 '12 at 10:59