Saturday 16 June 2012

Leting your vital javascript functions to do their job when the content changes

Hi Fellow Programmers

In this post I will show you one way to let your pages work as intended even if they are manipulated dynamically.

The problem: When the content of the page changes dynamically, those items are not listened by those javascript functions which were initialized at the time when the page loaded.

At the very first steps every programmer reinitializes only those handlers which are needed by the dynamically reloaded partial. This has some disadvantages. One of them is that if the initialization changes then it is very painful to track back the partials where the initialization need to be changed. Plus, the whole thing need a babysitting process...

I don't want that...

What I want is a structured way, in which is agile and robust enough to handle these issues... :)

Let me show you by code:
window.problemOrNot = { 
  vital_functions: [
    ->
      $(".cancel").click ->
        $('.cancelable_remove').remove()
        $('.cancelable_show').show()

  ]
  run_vital_functions: ->
    $.each problemOrNot.vital_functions, ->
      @()
}

jQuery ->
  problemOrNot.run_vital_functions()
And then in your partial, which obviously modifies your dom:
$('.comments').append("
  • <%=j render :partial => 'form' %>
  • "); ... ... ... $('#comment_operations').hide(); problemOrNot.run_vital_functions();
    That's it... The first code was in cofee script, and the partial was a rails .js.erb partial. :) Enjoy