Custom Javascript Events and Browser Support

Posted on Posted in Javascript, jQuery

Ok, so I am proud of myself lately for several reasons. I have made my first contributions to open source and they have been accepted! And also, I have found myself in need of and implementing my own custom events in Javascript.

So what am I doing?

Well, I want to use the new HTML5 fields for date and things like that. However, I want to have a fallback scenario for browsers that don’t support it. So what do you do?

Well, I am using jquery UI to implement the pickers for browsers that don’t support the date field. The data is being loaded via AJAX requests to templates and I am not sure how many fields are coming back. So what to do next?

Well, after the data is loaded, you can target the “date” type fields and then create the pickers that way. But how do you know the data is loaded? You can’t really use success on Ajax because the DOM may not be fully rendered when it attempts to instantiate the pickers on the fields. What to do?

Custom Events! You can setup your own events to be triggered. So in my case I have an event called ‘vendor:contentChange’ that lets me know when the container I am watching has it’s HTML content changed. I can then actually go through the new content and make adjustments. The beauty is that it happens when it needs to and I don’t have to artificially hold back instantiation by using setTimeout or something like that.

It’s very akin to a subscriber/listener pattern.

I can trigger that event whenever I want.

contentContainer.trigger('injury:contentChange');

This is a 2 part process though. I trigger the event and then I create the listener on the container.

contentContainer.on('injury:contentChange', contentFillCallback);

Ignore the poor choice in function names, but you should recognize this pattern. A more detailed in line version might look like.

contentContainer.on('injury:contentChange', function(){
   if ( $('[type="date"]').prop('type') != 'date' ) {
       $('[type="date"]').datepicker();
   }
});

Again, this is nothing new really. And I just thought I would share since is somewhat beyond your standard basic Javascript. I think everyone will eventually have to come across a solution like this. If you have ever said to yourself “Man, I need this script or function to run after this .” then consider this option.