Solved

Avoiding duplicate code in javascript

Posted on 2016-08-18
2
100 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 56

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

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Anyone familiar with PhotoSwipe? 3 21
PHP Web Development 6 30
How do i use the await event in php echo 5 19
boostsrap 1 13
PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
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…

730 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