[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Avoiding duplicate code in javascript

Posted on 2016-08-18
2
Medium Priority
?
231 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 9

Assisted Solution

by:James Bilous
James Bilous earned 600 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 60

Accepted Solution

by:
Julian Hansen earned 1400 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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
This article discusses how to implement server side field validation and display customized error messages to the client.
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…
Suggested Courses
Course of the Month18 days, 19 hours left to enroll

834 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