Oliver
Oliver

Reputation: 11597

Reuse of javascript code with asp.net

I've recently taken over development of a website written in asp.net. Before taking this on, I have spent very little time with web applications. As I have no experience in this area, I am hesitant to criticise, but I feel like this website is very badly written.

Look at the following search results produced by visual studio:

  \website\js\ADMIN_userprofile.js(715):function sendInvite() {
  \website\js\ADMIN_userprofilePro.js(745):function sendInvite() {
  \website\js\mycontactdetails.js(466):function sendInvite() {
  \website\js\mycontactdetailspro.js(466):function sendInvite() {
  \website\js\mycontactrequestspro.js(676):function sendInvite() {
  \website\js\mycontacts.js(239):function sendInvite()
  \website\js\mycontactspro.js(240):function sendInvite()
  \website\js\mygroups.js(103):function sendInvite()
  \website\js\myprofile.js(715):function sendInvite() {
  \website\js\myprofilepro.js(745):function sendInvite() {
  \website\js\search.js(55):function sendInvite() {    
  \website\js\searchpro.js(55):function sendInvite() {                         
  \website\search.js(44):function sendInvite() {

Each of those functions are the same. someone has copied the whole block of code whenenever they feel like another page needs the sendInvite() functionality. In the related .aspx pages, there is usually a link to click on that calls the function, and also a couple of hidden popups called by the javascript to say things like "Are you sure you want to send an invite?" in a way that agrees with the rest of the site design.

Cloned code is terrible, and very difficult to maintain. However, I don't know how to go about making this nicer. Can I wrap all the functionality here - the javascript and the popup stuff - into one device which I can reference wherever needed? I've read about the use of .ascx pages for this (sparingly used in the source code I have inherited), but I don't know if its safe to use these with javascript included too.

Upvotes: 1

Views: 463

Answers (3)

slandau
slandau

Reputation: 24052

Yeah man just take the method and put it in a .js file, pop it into a folder in your solution, and then in each .aspx page you need it, just import it:

<script type="text/javascript" src="<YOUR_LOCATION>"></script>

Upvotes: 1

DoctorMick
DoctorMick

Reputation: 6793

Shudder

There is nothing worse than code duplicated all over the place.

The simplest thing to do is copy the function in to a single js file, delete the code from all of the other js files and make sure the new script file is included in any pages that call one of the functions which use it using the script tag in the HTML.

Upvotes: 2

Raynos
Raynos

Reputation: 169391

Try a module manager for javascript like

Then place your functions in a module and require that module in your pages.

Upvotes: 2

Related Questions