重复使用相同的JavaScript与略有不同的应用程序

时间:2013-06-20 10:15:26

标签: javascript jquery

我有一个问题,我有一些代码,我想应用于两个略有不同的应用程序,但75%的代码将是相同的。这就是我喜欢的地方:

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()
      }
    });

  });
});

当按下提交表单按钮时,它将执行以下操作(此操作已经有效):

  1. 检查结果是否已从autosuggest点击
  2. 进行地理编码
  3. 如果没有,请使用地理编码
  4. 成功提交表格
  5. 当按下地理编码按钮时,我希望它执行以下操作(这不起作用):

    1. 检查结果是否已从autosuggest点击
    2. 进行地理编码
    3. 如果没有,请使用地理编码

    4. 所以我的问题是,我怎样才能这样做,这样我就可以为两个脚本使用相同的代码,而不必重复两次。我的想法是做以下事情:

      • 具有“提交表单”按钮的功能,其中包括提交表单
      • 具有地理编码按钮的功能,不包括提交表单

      我宁愿为每个按钮使用一个函数而不是使用某种标志,但我完全坚持如何实现它,每次我处理它时我最终完全破坏了脚本。任何帮助都会非常感激,因为我是javascript的新手,我正在努力解决这个问题。

1 个答案:

答案 0 :(得分:1)

如果唯一的区别是一个提交而另一个没有提交,则允许将回调传递给该函数,并且提交的回调可以将提交传递给该函数。

相关问题