0

I have a problem where I have some code which I want to apply to two slightly different applications, but 75% of the code will be the same. This is where I am with things:

http://jsfiddle.net/spadez/H6SZ2/6/

$(function () {
  var input = $("#loc"),
      lat   = $("#lat"),
      lng   = $("#lng"),
      lastQuery  = null,
      lastResult = null, // new!
      autocomplete;

  function processLocation(callback) { // accept a callback argument
    var query = $.trim(input.val()),
        geocoder;

    // if query is empty or the same as last time...
    if( !query || query == lastQuery ) {
      callback(lastResult); // send the same result as before
      return; // and stop here
    }

    lastQuery = query; // store for next time

    geocoder = new google.maps.Geocoder();
    geocoder.geocode({ address: query }, function(results, status) {
      if( status === google.maps.GeocoderStatus.OK ) {
        lat.val(results[0].geometry.location.lat());
        lng.val(results[0].geometry.location.lng());
        lastResult = true; // success!
      } else {
        alert("Sorry - We couldn't find this location. Please try an alternative");
        lastResult = false; // failure!
      }
      callback(lastResult); // send the result back
    });
  }

    var ctryiso = $("#ctry").val();
    var options = {
         types: ["geocode"]
    };
    if(ctryiso != ''){
        options.componentRestrictions= { 'country': ctryiso };        
    }
    autocomplete = new google.maps.places.Autocomplete(input[0], options); 


  google.maps.event.addListener(autocomplete, 'place_changed', processLocation);

  $('#search_form').on('submit', function (event) {
    var form = this;

    event.preventDefault(); // stop the submission

    processLocation(function (success) {
      if( success ) { // if the geocoding succeeded, submit the form
        form.submit()
      }
    });

  });
});

When the submit form button is pressed it will do the following (this works already):

  1. Check if result is already geocoded from autosuggest click
  2. If not, geocode
  3. Submit the form if successful

When the Geocode button is pressed I want it to do the following (this doesn't work):

  1. Check if result is already geocoded from autosuggest click
  2. If not, geocode

So my question is, how can I make it so I can use the same code for both scripts without having to duplicate it twice. My idea was to do the following:

  • Have a function for the "submit form" button which includes submitting the form
  • Have a function for the geocode button which does not include submitting the form

I would rather use a function for each button rather than using some kind of flag, but I am completely stuck on how to implement this, every time I work on it I end up breaking the script completely. I am new to JavaScript.

1 Answer 1

1

If the only difference is that one submits and the other does not, allow a callback to be passed into the function, and the one that submits can pass a submit to the function.

Sign up to request clarification or add additional context in comments.

9 Comments

This is a little bit advanced for me, I need to do some reading on this because I dont really understand callbacks at the moment
Give me a few minutes and I'll demonstrate. It's a rather simple concept, really.
Um, your two forms are identical! You cannot use an id more than once in a page.
Ok, I didn't realise. It's no issue for me to have different form names though for my usecase.
If I had realised how much of a mess your code was in, I wouldn't have volunteered to do this. However, I did, and I have. A few notes first. Don't use headings just for style! Use the appropriate markup and style with CSS. Learn how to form an input correctly! Don't repeat IDs in a page. I'm sure I found more, but that's just off the top of my head. I don't know if my solution works in your project, but it at least demonstrates how to keep the majority of your code while doing subtly different things. jsfiddle.net/H6SZ2/7
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.