Solved

Avoiding duplicate code in javascript

Posted on 2016-08-18
2
62 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 7

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 51

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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn how to dynamically set the form action using jQuery.
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)

743 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now