Solved

Avoiding duplicate code in javascript

Posted on 2016-08-18
2
74 Views
Last Modified: 2016-08-31
HI,
I have two javascript file as part of a web application which have almost the same function in it. I want to get rid of this duplicacy :
$("#submit").on("click", function(e) {
        var details = utils.getDetails(editor);
        var object = {
            name: $('#title').name(),
            data: editor.getData(),
            msg: $('#msg').val()
        };
        $.ajax({
            contentType: "application/json; charset=utf-8",
            type: "PUT",
            data: JSON.stringify(object),
            success: function(note, status, xhr) {
                  
            },
            error: function(request, status, error) {
                utils.error(text);
            }
        });
    });

Open in new window


Each js is included in a different page... I want to move these js out to a util.js file and avoid repeating the code here.
Also there are two differences between the javascript code above in the js files :
The other js file differs in the following place :
1)
 success: function(note, status, xhr) {
              lib.close()     // calls this inside the success handler
            },

2) POST //makes a post request

Need help separating out the common part...
Thanks
0
Comment
Question by:Rohit Bajaj
2 Comments
 
LVL 8

Assisted Solution

by:James Bilous
James Bilous earned 150 total points
ID: 41761482
You can create a function in util.js that takes the success function and type as parameters and simply substitutes them in the correct place. Then you can just call that function appropriately on each page.
0
 
LVL 54

Accepted Solution

by:
Julian Hansen earned 350 total points
ID: 41761542
I would structure it like this
function myAjaxWrapper(type, data)
{
  // details DOES NOT APPEAR TO BE USED SO REMOVE IT
  // var details = utils.getDetails(editor);
  return $.ajax({
    // url: ????????,
    contentType: "application/json; charset=utf-8",
    type: type,
    data: JSON.stringify(data)
  });
}

Open in new window

The above returns a promise - success and error are deprecated in later versions of jQuery.

With the promise you can do the following
// I WOULD PASS THIS AS A PARAMETER IT MAKES IT EASIER
// TO TEST
var object = {
  name: $('#title').name(),
  data: editor.getData(),
  msg: $('#msg').val()
};
myAjaxWrapper('PUT', object);
...
// then ON THE RETURNED PROMISE
// FIRES WHEN CALL IS SUCCESSFUL
// YOU CAN CUSTOMISE CALLBACK CODE
// ON DIFFERENT CALLS TO THE FUNCTION 
// WHERE THE CALL IS MADE
myAjaxWrapper('POST',object).then(function(resp) {
  lib.close();
});

Open in new window

If you are not familiar with promises you should read up on them - the above allows you to deal with the success call back in different ways depending on the context in which it is called.
0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

785 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question