0

I want to provide a way to use an on-event handler from the outside of a plugin. Problem is, that the trigger will not fired if I provide them in wrong order.

For example, this works:

$(window).on('foo:bar', function(){
    alert(true);
});
$(window).trigger('foo:bar');

...this, however does not:

$(window).trigger('foo:bar');
$(window).on('foo:bar', function(){
    alert(true);
});

Any ideas how the second approach can work?

Update

Here it works: http://www.benplum.com/projects/rubberband/

yckart
  • 32,460
  • 9
  • 122
  • 129

1 Answers1

2

You cannot. You want to eat cake before baking it.

UPD: You're misinterpreting the code at http://www.benplum.com/projects/rubberband/

Here is a jsfiddle with proof that it doesn't work like you're thinking: jsfiddle.net/zerkms/z5Mya/

Note about code: I've forked the library and added trivial console.log here: https://github.com/zerkms/Rubberband/blob/master/jquery.bp.rubberband.js#L77

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • Harr, nice answer! However, I've already seen that it works: https://github.com/benplum/Rubberband/blob/master/jquery.bp.rubberband.js#L79 – yckart Feb 15 '13 at 10:35
  • @yckart: I don't see where they add event handler – zerkms Feb 15 '13 at 10:42
  • @yckart: also check https://github.com/benplum/Rubberband/blob/master/jquery.bp.rubberband.js#L42 - that method is called **after** the handlers are attached – zerkms Feb 15 '13 at 10:43
  • No, they trigger the `rubberband` event with namespace `enter` and later it can used by the user to determine if an action was done: http://www.benplum.com/projects/rubberband/ (last section *examples*) The `rubberband`-event is never called in the plugin itself... – yckart Feb 15 '13 at 10:46
  • @yckart: nope, the `$(window).on` is called **before** the event is triggered - I've given you a link to `setTimeout` that delays triggering – zerkms Feb 15 '13 at 10:48
  • Yes, that the `setTimeout` triggers not the `rubberband` it triggers resize... or doesn't matter which event has been triggered? no! ;) – yckart Feb 15 '13 at 10:50
  • @yckart I think you're misreading that code. The triggers are only ever called in event handlers, one of which is the `_init` event, which is only called after all functions have been declared. None of the event handlers can be called before the function is declared - it's not possible – Reinstate Monica Cellio Feb 15 '13 at 10:51
  • Yes, Sorry! My fault, damn... Thanks! – yckart Feb 15 '13 at 10:54
  • I cannot give you more than 1 *+1* but I would ;-) – yckart Feb 15 '13 at 11:05