Solved

Avoiding duplicate code in javascript

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

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 57

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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
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)

719 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