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,719
  • 12
  • 50
  • 84
  • 7
    I think it really comes down to what the function does...A simple if check inside can work on both. – epascarello Jun 20 '13 at 14:32
  • you can move your function to a separate js. – Adil Shaikh Jun 20 '13 at 14:32
  • Why not using a single script file containing both functions and which would be included in both pages ? Btw, considering how http requests and connexions are slow, parsing the same small function twice is probably more efficient. – Virus721 Jun 20 '13 at 14:32
  • `$('a').click(function(){if($(this).hasClass('dialog')) { DO SOMETHING..}...` – ayyp Jun 20 '13 at 14:33

2 Answers2

2
function Function1() {
  $('a').click(function(event){
     if($(this).is('.dialog')) //or .hasClass('dialog')
         //...
     else //...
  });
};
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • 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,662
  • 5
  • 50
  • 75
  • 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