]> git.openstreetmap.org Git - rails.git/commitdiff
Refactor out 'globals' from more functions
authorTom MacWright <tom@macwright.org>
Tue, 11 Jun 2013 20:09:19 +0000 (13:09 -0700)
committerJohn Firebaugh <john.firebaugh@gmail.com>
Thu, 18 Jul 2013 17:45:13 +0000 (10:45 -0700)
app/assets/javascripts/application.js
app/assets/javascripts/browse.js
app/assets/javascripts/index.js
app/assets/javascripts/querystring.js

index 247df1b8360f2eda5ee293cef1014336d63ae698..a7548e7f9cbff9a7175a431bd0912ae0394aef2e 100644 (file)
@@ -19,7 +19,7 @@
 //= require geocoder
 //= require querystring
 
-var querystring = require('querystring');
+var querystring = require('querystring-component');
 
 function zoomPrecision(zoom) {
     var decimals = Math.pow(10, Math.floor(zoom/3));
@@ -35,6 +35,27 @@ function normalBounds(bounds) {
         new L.LatLng(bounds[1][0], bounds[1][1]));
 }
 
+function remoteEditHandler(bbox, select) {
+  var loaded = false,
+      query = {
+          left: bbox.getWest() - 0.0001,
+          top: bbox.getNorth() + 0.0001,
+          right: bbox.getEast() + 0.0001,
+          bottom: bbox.getSouth() - 0.0001
+      };
+
+  if (select) query.select = select;
+  $("#linkloader")
+    .attr("src", "http://127.0.0.1:8111/load_and_zoom?" + querystring.stringify(query))
+    .load(function() { loaded = true; });
+
+  setTimeout(function () {
+    if (!loaded) alert(I18n.t('site.index.remote_failed'));
+  }, 1000);
+
+  return false;
+}
+
 /*
  * Called as the user scrolls/zooms around to maniplate hrefs of the
  * view tab and various other links
@@ -63,9 +84,9 @@ function updatelinks(loc, zoom, layers, bounds, object) {
 
     if ($(link).hasClass("llz")) {
       $.extend(args, {
-          lat: '' + lat,
-          lon: '' + lon,
-          zoom: '' + zoom
+          lat: lat,
+          lon: lon,
+          zoom: zoom
       });
     } else if (minlon && $(link).hasClass("bbox")) {
       $.extend(args, {
@@ -103,17 +124,13 @@ function minZoomAlert() {
     alert(I18n.t("javascripts.site." + name + "_zoom_alert")); return false;
 }
 
-/*
- * Called to create a short code for the short link.
- */
+// Called to create a short code for the short link.
 function makeShortCode(map) {
-    var lon = map.getCenter().lng,
-        lat = map.getCenter().lat,
-        zoom = map.getZoom(),
+    var zoom = map.getZoom(),
         str = '',
         char_array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_~",
-        x = Math.round((lon + 180.0) * ((1 << 30) / 90.0)),
-        y = Math.round((lat +  90.0) * ((1 << 30) / 45.0)),
+        x = Math.round((map.getCenter().lng + 180.0) * ((1 << 30) / 90.0)),
+        y = Math.round((map.getCenter().lat +  90.0) * ((1 << 30) / 45.0)),
         // JavaScript only has to keep 32 bits of bitwise operators, so this has to be
         // done in two parts. each of the parts c1/c2 has 30 bits of the total in it
         // and drops the last 4 bits of the full 64 bit Morton code.
index 9caaa3714516a9c38e7be80ca1b985e7d3a43035..c39e8382c6dc8d1ab445bfcf97770614cee3f0f5 100644 (file)
@@ -1,31 +1,4 @@
 $(document).ready(function () {
-  function remoteEditHandler(bbox, select) {
-    var left = bbox.getWest() - 0.0001;
-    var top = bbox.getNorth() + 0.0001;
-    var right = bbox.getEast() + 0.0001;
-    var bottom = bbox.getSouth() - 0.0001;
-    var loaded = false;
-
-    $("#linkloader").load(function () { loaded = true; });
-
-    var query = {
-        left: left,
-        top: top,
-        right: right,
-        bottom: bottom,
-        select: select
-    };
-
-    if (select) query.select = select;
-    $("#linkloader").attr("src", "http://127.0.0.1:8111/load_and_zoom?" +
-      querystring.stringify(query));
-
-    setTimeout(function () {
-      if (!loaded) alert(I18n.t('site.index.remote_failed'));
-    }, 1000);
-
-    return false;
-  }
 
   var map = L.map("small_map", {
     attributionControl: false,
index 10f9f86f065d6fd78ffd3ff59d4744921f739e0a..753cf474013e2519e86104dc2b8450358b74f5d1 100644 (file)
@@ -9,20 +9,8 @@
 //= require index/key
 //= require index/notes
 
-var map, layers; // TODO: remove globals
-
-$(document).ready(function () {
-  var marker;
-  var params = OSM.mapParams();
-
-  var map = L.map("map", {
-    zoomControl: false,
-    layerControl: false
-  });
-
-  map.attributionControl.setPrefix('');
-
-  layers = [{
+function allLayers() {
+  return [{
     layer: new L.OSM.Mapnik({
       attribution: '',
       code: "M"
@@ -51,6 +39,19 @@ $(document).ready(function () {
     keyid: "mapquest",
     name: I18n.t("javascripts.map.base.mapquest")
   }];
+}
+
+$(document).ready(function () {
+  var params = OSM.mapParams();
+
+  var map = L.map("map", {
+    zoomControl: false,
+    layerControl: false
+  });
+
+  map.attributionControl.setPrefix('');
+
+  var layers = allLayers();
 
   layers[0].layer.addTo(map);
 
@@ -74,18 +75,14 @@ $(document).ready(function () {
     uiPane: uiPane
   }).addTo(map);
 
-  L.control.note({
-    position: 'topright'
-  }).addTo(map);
-
-  L.control.locate({
-    position: 'topright'
-  }).addTo(map);
-
+  L.control.note({ position: 'topright' }).addTo(map);
+  L.control.locate({ position: 'topright' }).addTo(map);
   L.control.scale().addTo(map);
 
   map.on('moveend layeradd layerremove', updateLocation);
 
+  map.markerLayer = L.layerGroup().addTo(map);
+
   if (!params.object_zoom) {
     if (params.bbox) {
       var bbox = L.latLngBounds([params.minlat, params.minlon],
@@ -121,7 +118,7 @@ $(document).ready(function () {
   }
 
   if (params.marker) {
-    marker = L.marker([params.mlat, params.mlon], {icon: getUserIcon()}).addTo(map);
+    L.marker([params.mlat, params.mlon], {icon: getUserIcon()}).addTo(map.markerLayer);
   }
 
   if (params.object) {
@@ -130,90 +127,21 @@ $(document).ready(function () {
 
   handleResize();
 
-  $("body").on("click", "a.set_position", function (e) {
-    e.preventDefault();
+  $("body").on("click", "a.set_position", setPositionLink(map));
 
-    var data = $(this).data();
-    var centre = L.latLng(data.lat, data.lon);
-
-    if (data.minLon && data.minLat && data.maxLon && data.maxLat) {
-      map.fitBounds([[data.minLat, data.minLon],
-                     [data.maxLat, data.maxLon]]);
-    } else {
-      map.setView(centre, data.zoom);
-    }
-
-    if (data.type && data.id) {
-      addObjectToMap(data, map, { zoom: true, style: { opacity: 0.2, fill: false } });
-    }
-
-    if (marker) {
-      map.removeLayer(marker);
-    }
-
-    marker = L.marker(centre, {icon: getUserIcon()}).addTo(map);
+  $("a[data-editor=remote]").click(function(e) {
+      remoteEditHandler(map.getBounds());
+      e.preventDefault();
   });
 
-  // generate a cookie-safe string of map state
-  function cookieContent(map) {
-    var center = map.getCenter().wrap();
-    return [center.lng, center.lat, map.getZoom(), getMapLayers(map)].join('|');
-  }
-
-  function updateLocation() {
-    updatelinks(map.getCenter().wrap(),
-        map.getZoom(),
-        getMapLayers(this),
-        map.getBounds().wrap(),
-        params.object);
-
-    var expiry = new Date();
-    expiry.setYear(expiry.getFullYear() + 10);
-    $.cookie("_osm_location", cookieContent(map), { expires: expiry });
-  }
-
-  function remoteEditHandler() {
-    var extent = map.getBounds();
-    var loaded = false;
-
-    $("#linkloader").load(function () { loaded = true; });
-    $("#linkloader").attr("src", "http://127.0.0.1:8111/load_and_zoom?" +
-         querystring.stringify({
-            left: extent.getWest(),
-            bottom: extent.getSouth(),
-            right: extent.getEast(),
-            top: extent.getNorth()
-         }));
-
-    setTimeout(function () {
-      if (!loaded) alert(I18n.t('site.index.remote_failed'));
-    }, 1000);
-
-    return false;
-  }
-
-  $("a[data-editor=remote]").click(remoteEditHandler);
-
   if (OSM.preferred_editor == "remote" && $('body').hasClass("site-edit")) {
-    remoteEditHandler();
+    remoteEditHandler(map.getBounds());
   }
 
   $(window).resize(handleResize);
 
-  $("#search_form").submit(function () {
-    var bounds = map.getBounds();
+  $("#search_form").submit(submitSearch(map));
 
-    $("#sidebar_title").html(I18n.t('site.sidebar.search_results'));
-    $("#sidebar_content").load($(this).attr("action"), {
-      query: $("#query").val(),
-      minlon: bounds.getWest(),
-      minlat: bounds.getSouth(),
-      maxlon: bounds.getEast(),
-      maxlat: bounds.getNorth()
-    }, openSidebar);
-
-    return false;
-  });
 
   if ($("#query").val()) {
     $("#search_form").submit();
@@ -226,6 +154,7 @@ $(document).ready(function () {
   }
 });
 
+// non-scoped utilities
 function getMapBaseLayer() {
   for (var i = 0; i < layers.length; i++) {
     if (map.hasLayer(layers[i].layer)) {
@@ -244,3 +173,60 @@ function getMapLayers(map) {
   }
   return layerConfig;
 }
+
+// generate a cookie-safe string of map state
+function cookieContent(map) {
+  var center = map.getCenter().wrap();
+  return [center.lng, center.lat, map.getZoom(), getMapLayers(map)].join('|');
+}
+
+function updateLocation() {
+  updatelinks(this.getCenter().wrap(),
+      this.getZoom(),
+      getMapLayers(this),
+      this.getBounds().wrap(), {});
+
+  var expiry = new Date();
+  expiry.setYear(expiry.getFullYear() + 10);
+  $.cookie("_osm_location", cookieContent(this), { expires: expiry });
+}
+
+function setPositionLink(map) {
+  return function(e) {
+      var data = $(this).data(),
+          center = L.latLng(data.lat, data.lon);
+
+      if (data.minLon && data.minLat && data.maxLon && data.maxLat) {
+        map.fitBounds([[data.minLat, data.minLon],
+                       [data.maxLat, data.maxLon]]);
+      } else {
+        map.setView(center, data.zoom);
+      }
+
+      if (data.type && data.id) {
+        addObjectToMap(data, map, { zoom: true, style: { opacity: 0.2, fill: false } });
+      }
+
+      map.markerLayer.clearLayers();
+      L.marker(center, {icon: getUserIcon()}).addTo(map.markerLayer);
+
+      return e.preventDefault();
+  };
+}
+
+function submitSearch(map) {
+  return function(e) {
+    var bounds = map.getBounds();
+
+    $("#sidebar_title").html(I18n.t('site.sidebar.search_results'));
+    $("#sidebar_content").load($(this).attr("action"), {
+      query: $("#query").val(),
+      minlon: bounds.getWestLng(),
+      minlat: bounds.getSouthLat(),
+      maxlon: bounds.getEastLng(),
+      maxlat: bounds.getNorthLat()
+    }, openSidebar);
+
+    return e.preventDefault();
+  };
+}
index 16aa63c4558bf344e0c7002a515f7616419b8d69..24e4382ad3634d46ee3c178617378101a7f8995f 100644 (file)
@@ -1,46 +1,15 @@
-require=(function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i})({"querystring":[function(require,module,exports){
-module.exports=require('SIBfUI');
-},{}],"SIBfUI":[function(require,module,exports){
-var isArray = typeof Array.isArray === 'function'
-    ? Array.isArray
-    : function (xs) {
-        return Object.prototype.toString.call(xs) === '[object Array]'
-    };
-
-var objectKeys = Object.keys || function objectKeys(object) {
-    if (object !== Object(object)) throw new TypeError('Invalid object');
-    var keys = [];
-    for (var key in object) if (object.hasOwnProperty(key)) keys[keys.length] = key;
-    return keys;
-}
-
-
-/*!
- * querystring
- * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
- * MIT Licensed
- */
+require=(function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i})({"querystring-component":[function(require,module,exports){
+module.exports=require('Xr2wId');
+},{}],"Xr2wId":[function(require,module,exports){
 
 /**
- * Library version.
+ * Module dependencies.
  */
 
-exports.version = '0.3.1';
+var trim = require('trim');
 
 /**
- * Object#toString() ref for stringify().
- */
-
-var toString = Object.prototype.toString;
-
-/**
- * Cache non-integer test regexp.
- */
-
-var notint = /[^0-9]/;
-
-/**
- * Parse the given query `str`, returning an object.
+ * Parse the given query `str`.
  *
  * @param {String} str
  * @return {Object}
@@ -48,209 +17,55 @@ var notint = /[^0-9]/;
  */
 
 exports.parse = function(str){
-  if (null == str || '' == str) return {};
-
-  function promote(parent, key) {
-    if (parent[key].length == 0) return parent[key] = {};
-    var t = {};
-    for (var i in parent[key]) t[i] = parent[key][i];
-    parent[key] = t;
-    return t;
+  if ('string' != typeof str) return {};
+
+  str = trim(str);
+  if ('' == str) return {};
+
+  var obj = {};
+  var pairs = str.split('&');
+  for (var i = 0; i < pairs.length; i++) {
+    var parts = pairs[i].split('=');
+    obj[parts[0]] = null == parts[1]
+      ? ''
+      : decodeURIComponent(parts[1]);
   }
 
-  return String(str)
-    .split('&')
-    .reduce(function(ret, pair){
-      try{ 
-        pair = decodeURIComponent(pair.replace(/\+/g, ' '));
-      } catch(e) {
-        // ignore
-      }
-
-      var eql = pair.indexOf('=')
-        , brace = lastBraceInKey(pair)
-        , key = pair.substr(0, brace || eql)
-        , val = pair.substr(brace || eql, pair.length)
-        , val = val.substr(val.indexOf('=') + 1, val.length)
-        , parent = ret;
-
-      // ?foo
-      if ('' == key) key = pair, val = '';
-
-      // nested
-      if (~key.indexOf(']')) {
-        var parts = key.split('[')
-          , len = parts.length
-          , last = len - 1;
-
-        function parse(parts, parent, key) {
-          var part = parts.shift();
-
-          // end
-          if (!part) {
-            if (isArray(parent[key])) {
-              parent[key].push(val);
-            } else if ('object' == typeof parent[key]) {
-              parent[key] = val;
-            } else if ('undefined' == typeof parent[key]) {
-              parent[key] = val;
-            } else {
-              parent[key] = [parent[key], val];
-            }
-          // array
-          } else {
-            obj = parent[key] = parent[key] || [];
-            if (']' == part) {
-              if (isArray(obj)) {
-                if ('' != val) obj.push(val);
-              } else if ('object' == typeof obj) {
-                obj[objectKeys(obj).length] = val;
-              } else {
-                obj = parent[key] = [parent[key], val];
-              }
-            // prop
-            } else if (~part.indexOf(']')) {
-              part = part.substr(0, part.length - 1);
-              if(notint.test(part) && isArray(obj)) obj = promote(parent, key);
-              parse(parts, obj, part);
-            // key
-            } else {
-              if(notint.test(part) && isArray(obj)) obj = promote(parent, key);
-              parse(parts, obj, part);
-            }
-          }
-        }
-
-        parse(parts, parent, 'base');
-      // optimize
-      } else {
-        if (notint.test(key) && isArray(parent.base)) {
-          var t = {};
-          for(var k in parent.base) t[k] = parent.base[k];
-          parent.base = t;
-        }
-        set(parent.base, key, val);
-      }
-
-      return ret;
-    }, {base: {}}).base;
+  return obj;
 };
 
 /**
- * Turn the given `obj` into a query string
+ * Stringify the given `obj`.
  *
  * @param {Object} obj
  * @return {String}
  * @api public
  */
 
-var stringify = exports.stringify = function(obj, prefix) {
-  if (isArray(obj)) {
-    return stringifyArray(obj, prefix);
-  } else if ('[object Object]' == toString.call(obj)) {
-    return stringifyObject(obj, prefix);
-  } else if ('string' == typeof obj) {
-    return stringifyString(obj, prefix);
-  } else {
-    return prefix;
+exports.stringify = function(obj){
+  if (!obj) return '';
+  var pairs = [];
+  for (var key in obj) {
+    pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
   }
+  return pairs.join('&');
 };
 
-/**
- * Stringify the given `str`.
- *
- * @param {String} str
- * @param {String} prefix
- * @return {String}
- * @api private
- */
-
-function stringifyString(str, prefix) {
-  if (!prefix) throw new TypeError('stringify expects an object');
-  return prefix + '=' + encodeURIComponent(str);
-}
-
-/**
- * Stringify the given `arr`.
- *
- * @param {Array} arr
- * @param {String} prefix
- * @return {String}
- * @api private
- */
-
-function stringifyArray(arr, prefix) {
-  var ret = [];
-  if (!prefix) throw new TypeError('stringify expects an object');
-  for (var i = 0; i < arr.length; i++) {
-    ret.push(stringify(arr[i], prefix + '[]'));
-  }
-  return ret.join('&');
-}
-
-/**
- * Stringify the given `obj`.
- *
- * @param {Object} obj
- * @param {String} prefix
- * @return {String}
- * @api private
- */
-
-function stringifyObject(obj, prefix) {
-  var ret = []
-    , keys = objectKeys(obj)
-    , key;
-  for (var i = 0, len = keys.length; i < len; ++i) {
-    key = keys[i];
-    ret.push(stringify(obj[key], prefix
-      ? prefix + '[' + encodeURIComponent(key) + ']'
-      : encodeURIComponent(key)));
-  }
-  return ret.join('&');
-}
+},{"trim":1}],1:[function(require,module,exports){
 
-/**
- * Set `obj`'s `key` to `val` respecting
- * the weird and wonderful syntax of a qs,
- * where "foo=bar&foo=baz" becomes an array.
- *
- * @param {Object} obj
- * @param {String} key
- * @param {String} val
- * @api private
- */
+exports = module.exports = trim;
 
-function set(obj, key, val) {
-  var v = obj[key];
-  if (undefined === v) {
-    obj[key] = val;
-  } else if (isArray(v)) {
-    v.push(val);
-  } else {
-    obj[key] = [v, val];
-  }
+function trim(str){
+  return str.replace(/^\s*|\s*$/g, '');
 }
 
-/**
- * Locate last brace in `str` within the key.
- *
- * @param {String} str
- * @return {Number}
- * @api private
- */
+exports.left = function(str){
+  return str.replace(/^\s*/, '');
+};
 
-function lastBraceInKey(str) {
-  var len = str.length
-    , brace
-    , c;
-  for (var i = 0; i < len; ++i) {
-    c = str[i];
-    if (']' == c) brace = false;
-    if ('[' == c) brace = true;
-    if ('=' == c && !brace) return i;
-  }
-}
+exports.right = function(str){
+  return str.replace(/\s*$/, '');
+};
 
 },{}]},{},[])
 ;
\ No newline at end of file