Skip to content

Instantly share code, notes, and snippets.

@jupiterjs
Created February 9, 2011 04:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jupiterjs/817879 to your computer and use it in GitHub Desktop.
Save jupiterjs/817879 to your computer and use it in GitHub Desktop.
Async Events and Event Oriented Architectures

Event Oriented Architectures

When building JavaScript widgets, they should communicate with "outside" code similar to how native elements, especially form elements work. For example:

The anchor element.

Default Event: window.location = el.href Prevent Default : $(el).click(function(ev){ev.preventDefault()})

The form element.

Default Event: $.post(el.action,$(el).serialize()) Prevent Default : $(el).submit(function(ev){ev.preventDefault()})

Implementing EOA widgets with jQuery

Now think about a tabs widget. You could provide a default 'show' event that people could prevent like:

$('.tab').bind('default.show', function(){
  $(this).show
});

The ideas behind this are discussed here: [http://jupiterjs.com/news/jquery-default-events].

Why Async?

Building our Event Oriented Architectures, we keep running into the problem of how to handle asynchronous behavior. For example, a tabs widget might call 'show' on a panel.

BUT, you might want to customize the panel to do an Ajax request for data before the panel is actually shown. I'm considering trying to provide a pause and resume method on events that would allow the following:

$(".panel").bind("show", function(ev){
  ev.pause();
  var panel = $(this);
  $.get(this.id, {}, function(html){
    panel.html(html);
    ev.resume();  
  }, 'html')
});

This would work well with our default events plugin: http://jupiterjs.com/news/jquery-default-events . The tabs widget would have something like the following:

$(".panel").bind("default.show", function(ev){
  $(this).show()
});

Essentially, you can prevent future event handlers from being called and have them resumed at some later point. In this tabs widget, it would prevent the tab panel from being shown until the HTML has been updated by the Ajax request. I think this would add a lot of power along side preventDefault.

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