2

I am struggling on how to organise my jquery code.

I have the following functions:

function Function1() {
  $('a').not('a.dialog').click(function(event){
    // Do something.
  });
};

function Function2() {
  $('a.dialog').click(function () {
    // Do something.
  });
};

Function1 is called on every page, function2 is called only on a single page.

What is the best way to remove the duplication between these two functions specifically the reference to 'a.dialog'.

Should I be using global variables? or is the above code the best I can hope for?

------------------ UPDATE ------------------

The specifics of the two functions are as follows:

Function1 does this: iPhone Safari Web App opens links in new window

Function2 opens a dialog lightbox.

Community
  • 1
  • 1
pingu
  • 8,649
  • 10
  • 47
  • 84

2 Answers2

2
function Function1() {
  $('a').click(function(event){
     if($(this).is('.dialog')) //or .hasClass('dialog')
         //...
     else //...
  });
};
A. Wolff
  • 73,242
  • 9
  • 90
  • 149
  • This would work, however I would prefer to keep the separation between the two functions. Also this solution would introduce an "if" overhead for most of the pages on the site. – pingu Jun 20 '13 at 14:49
  • in the if part (for dialog) you could call a external function setted inside the specific page – A. Wolff Jun 20 '13 at 14:55
  • If you want separation than why do you think you need to combine them in the first place! – epascarello Jun 20 '13 at 15:11
  • @epascarello - to avoid duplication, as more likely to introduce bugs. Also to avoid the repeat search overhead. – pingu Jun 20 '13 at 15:20
  • 2
    Don't worry about `if` overhead, you can execute it tens or hundreds of millions of times before reaching the perceivable 100ms lag threshold... – Esailija Jun 20 '13 at 15:39
1

One way could be to do it like that :

$('a').click(function(){
    alert('work');
})

$('.dialog').unbind().click(function(){
    alert('really work')
})

Reduce the number of if...

Fiddle : http://jsfiddle.net/SJvrD/

Karl-André Gagnon
  • 33,269
  • 5
  • 49
  • 72
  • 2
    "As of jQuery 1.7, the .on() and .off() methods are preferred to attach and remove event handlers on elements." - just FYI. I imagine they will eventually be deprecated. – rlemon Jun 20 '13 at 15:48