Loading...
Loading...
Marco Franssen

In this post, I'll show how jQuery events can help keep JavaScript modules separate while still letting them communicate. Many developers dislike JavaScript for various reasons, but I think it's a pretty cool language. Writing clear JavaScript can make it more approachable and encourage more developers to give it a try.
I'll use jQuery to write OOP-style JavaScript, an approach you might recognize from languages like c#. Here's what I want to achieve: two modules, one for a jQuery dialog containing a form to submit products, and another for a grid showing those products. For the grid, you could use jqGrid, for example. I want the modules to operate independently while still being able to communicate. That's where the jQuery event mechanism comes in.
First, I'll create my JavaScript productDialog module.
var productDialog = function($){
var self = null;
var dialogForm = null;
var init = function() {
if (self === null) return;
self = this;
initDialog();
};
var initDialog = function() {
dialogForm = $('#productDialogForm');
dialogForm.dialog({
autoOpen: false,
height: 300,
width: 350,
buttons: {
Create: function() {
var valid = true;
//Some form validation, left for brevity
if(valid) {
$.post('someserverurl', formData, postComplete, 'json');
}
},
Cancel: function() {
$(this).dialog('close');
}
},
close: function() {
//remove validation classes from form elements
//left for brevity
}
});
//Do some cool jquery stuff on your form to make it more interactive
//Remove the original submit button because dialog contains one
}
var postComplete = function(data) {
self.trigger('formPostComplete', data); //triggers event with the response from the server
};
var show = function(modal) {
if (modal) dialogForm.dialog({ modal: true; });
else dialogForm.dialog({ modal: false; });
dialogForm.dialog('open');
};
return {
init: init,
showModal: show(true),
show: show
};
}(jQuery);Next, I need to initialize the products overview.
var productOverview = (function ($) {
var self = null;
var grid = null;
var init = function () {
if (self === null) return;
self = this;
grid = $("#productsGrid");
//init a jqGrid on some div id grid.jqGrid(....
//or simply init some other things to show your products data by doing a $.get(....
//left for brevity
};
var refreshData = function (data) {
//simply call grid.reload() in case of jqGrid,
//or update your products overview by using the data, (depends on what your server post returns)
//or do a $.get request or something
};
return {
init: init,
refreshData: refreshData,
};
})(jQuery);To let the modules communicate on a specific page, I'll implement a mediator that connects their logic. At first glance, this might look like overkill. I can hear you thinking, "Why not do this in the page itself?" Well, as your modules gain more events and more logic to connect, that code can grow. When the number of modules on a page grows, it's useful to have a central place to connect them. You can use multiple mediators if that keeps your code cleaner.
var productMediator = (function ($) {
var self = null;
var init = function () {
if (self === null) return;
self = null;
productDialog.init();
productOverview.init();
productDialog.bind("formPostComplete", productOverview.refreshData);
$("#createNewProduct").click(productDialog.showModal); //binds buttonclick
};
return {
init: init,
};
})(jQuery);Last but not least, add these scripts to your page.
<!DOCTYPE html>
<html>
<head>
<title>Products</title>
<!-- stylesheets jquery ui and ui dialog-->
<!-- scripts jquery and jquery ui-->
<script src="productDialog.js"></script>
<script src="productOverview.js"></script>
<script src="productMediator.js"></script>
<script>
$(function() {
productMediator.init();
});
</script>
</head>
<body>
<h1>Products<h1>
<button id="createNewProduct">Create new product</button>
<div id="productsGrid">
<!-- Contains your products grid -->
<div>
<form id="productDialogForm">
<label for="name">Name</label>
<input id="name" name="name" />
<label for="price">Price</label>
<input id="price" name="price" />
<label for="category">Category</label>
<input id="category" name="category" />
<button type="submit">Create</button>
</form>
</body>
</html>I hope this code makes JavaScript feel a little less intimidating. The modules shown here can be used independently; the mediator is what connects them. You can easily combine them with MVC 3 partials containing the HTML, for example. The returned object controls which methods are publicly accessible. I hope this has made it easier to get started writing your own JavaScript apps. Maybe you'll soon be writing some cool Windows 8 JavaScript apps.
As always, share this post if you liked it! If you didn't, share it anyway :D.
Marco Franssen
See how I wrapped the Ncqrs command service to retry commands after concurrency exceptions, with results from a simple asynchronous JavaScript test.
Marco Franssen
Install Windows 8 Developer Preview on a virtual hard disk and boot it alongside Windows 7, using a bootable USB drive and diskpart.
Marco Franssen
Try Windows 8 Developer Preview in VirtualBox with this walkthrough of hardware requirements, virtual machine settings, and the installation wizard.
Marco Franssen
Build country, state, and city dropdowns with Knockout.js observables and jQuery JSON requests, with an ASP.NET MVC 3 server-side example.