Blog.

jQuery events contributes to clean Javascript

MF

Marco Franssen /

5 min read827 words

Cover Image for jQuery events contributes to clean Javascript

As the title reveals, this blogpost is about some clean javascript code example. Many developers dislike javascript because of different reasons. I think javascript is a pretty cool language. To prevent developers from disliking it and encourage them to show how great javascript can be, we all as developers have to write javascript in a clean way. This way lesser developers will be discouraged to use it.

In this blogpost I will show you how to write some OOP style javascript, which you know as of languages like c#. I will use jQuery to get to some clean javascript code. First of all I explain what I try to achieve with this code. I want to make two modules, one is a jQuery dialog which contains a form to post some products, the other one is some grid that shows the products. For this second one you could use for example jqGrid. I want these two modules to operate completely seperate from each other. They should be able to communicate with each other. Therefore I will use the jQuery event mechanism.

So first of all I will 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);

Second I need to init my 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);

In order to let them communicate with each other on a specific page I implement some mediator, who will link some logic together for a specific page. At first glance this looks like overkill, and I see you thinking why not ding this in the page itself. Well when your modules have more events and more logic to link to each other this can grow into larger code. When the amount of modules on a page grows, you want a central place where you link all logic together. You can implement more mediators in case this 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 you have to 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>

Conclusion

This code doesn't look discouraging at all and I hope it didn't do for you. The modules I showed you of here can be used seperately from each other except for the mediator. You can combine them easy with some mvc3 partials, which include the html for example. You can control which methods are public visible in the return value. I hope I lowered the threshold to write some javascript apps yourself. Maybe you're writing very soon some cool Windows 8 javascript apps.

As always, share this post if you liked it! If you didn't also share it :D.

You have disabled cookies. To leave me a comment please allow cookies at functionality level.

More Stories

Cover Image for Auto retry concurrent commands with ncqrs

Auto retry concurrent commands with ncqrs

MF

Marco Franssen /

In a previous post I showed you some pseudo code Gregory Young mentioned in his DDD CQRS course I attended in Krakow, Poland. In this course Greg made clear to us locking of databases isn't necessary. He showed us some pseudo code how to easily write a merge handler to handle all concurrency conflicts. In my current project, based on the ncqrs-framework I implemented a simpler version of this merge handler which only retries each command if a ConcurrencyException occurs. To achieve this you can…

Cover Image for Install and boot Windows 8 from vhd

Install and boot Windows 8 from vhd

MF

Marco Franssen /

In a previous blog post I explained to you how to install Windows 8 in a virtual machine in VirtualBox. In VirtualBox I used 1GB of memory and 2 of my cores and it performed quite good. However in the metro interface I had some issues with my mouse (scrolling, delays etc.) So yesterday I decided to install Windows 8 on a vhd and boot directly from it. To do so I followed Scott Hanselman's blog post. Below I placed a shorter summary for you guys: Step 0 Make sure you have at least 40GB of free…

Cover Image for Install Win 8 developer preview in your VirtualBox

Install Win 8 developer preview in your VirtualBox

MF

Marco Franssen /

Since today you can download the pre-release of Windows 8 (Developer preview). Since testing this new stuff out can be risky, it is best you do it in a virtual machine. You can download it the developer preview from the new Windows Dev Center. MSDN subscribers can download some additional win8 stuff. Before you start you have to make sure your pc supports hardware virtualization. Here you can find how to enable it in the BIOS if your system supports it. https://www.microsoft.com/windows/virtual…

Cover Image for Knockout that cascading dropdown

Knockout that cascading dropdown

MF

Marco Franssen /

In this article I will explain how you can make cascading dropdowns with Knockout.js. Knockout.js is a JavaScript library which provides you some stuff to implement the MVVM pattern.  Knockout provides you the following stuff: Declarative bindings: (Easily associate DOM elements with model data using a concise, readable syntax); Automatic UI Refresh: (When your data model's state changes, your UI updates automatically) Dependency tracking: (Implicitly set up chains of relationships between mo…