rob.m
rob.m

Reputation: 10611

How to avoid duplication of code if this needs to be called afer an ajax call too?

I have 2 situations:

  1. I am loading content with ajax
  2. I have a search result page where the content is not loaded with ajax

I do have lots of jQuery happening which targets the content in the page, be this loaded with ajax or simply printed on the page.

So as a callback for the ajax content I have:

jQuery.fn.almComplete = function(alm){
 ..MY CODE..
});

However ..MY CODE.. is also needed for content loaded without ajax.

I would like to avoid duplicating the code by placing it before and after the ajax callback for example

Upvotes: 2

Views: 89

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337713

You can place the code within the AJAX callback handler within its own function. You can then call this function on load of the page, and pass it's reference to the handler. Try this:

function updateUi(alm) {
    // Your code...
}

updateUi('foobar'); // onload
jQuery.fn.almComplete = updateUi; // on AJAX completion

Upvotes: 4

Related Questions