Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the best way to resolve name conflicts in javascript?

Tags:

javascript

I recently wrote some javascript code that filled a drop down list based on some XML, pretty simple stuff. The problem was I had to write similar code to do almost the same thing on a different page.

Because the code was almost identical I named most of the functions the same, thinking that they would never be included in the same page. However, naming conflicts arose because both javascript files were eventually included in the same HTML page.

When I had to go back and change the names I simply added first_ or second_ to the method's names. This was a pain and it doesn't seem very elegant to me. I was wondering if there is a better way to resolve name conflicts in javascript?

like image 741
ForYourOwnGood Avatar asked Dec 30 '08 22:12

ForYourOwnGood


1 Answers

Try the JavaScript module pattern (or namespaces) used in various libraries.

Try to be DRY (don't repeat yourself) so you can avoid name collisions. If the code is almost the same you better avoid code duplication by creating a function which can handle both cases. The function can take two parameters: which dropdown to populate and with what data. This helps maintainability as well.

update: I assume that you take the XML from an AJAX request. In this case you can create on-the-fly anonymous functions with the appropriate parameters for callback inside a loop.

like image 92
bandi Avatar answered Sep 22 '22 19:09

bandi