如何在对象和DRY中移动javascript函数?

时间:2012-04-25 11:07:45

标签: javascript google-maps javascript-events javascript-objects

在下面给出的函数中重复相同的操作。我想尽可能多地移动到物体上。也许可以直接从按钮一次初始化对象中的正确方法?

HTML:

<div id="map" style="width: 500px; height: 400px;"></div>
<button onclick="drawPoly()">Draw This Poly</button>
<button onclick="newPoly()">Create New Poly</button>
<button onclick="restorePolys()">Restore Polys</button>
<button onclick="dropMarker()">Drop Marker</button>

JS:

var map;
var mapListener = null;

$(function() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: new google.maps.LatLng(48.864715, 10.546875),
        zoom: 4,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
});

dropMarker = function() {
    if ( !! mapListener) google.maps.event.removeListener(mapListener);

    mapListener = google.maps.event.addListener(map, 'click', function(e) {
        tools.createMarker(e.latLng);
    });
}

drawPolyline = function() {
    if ( !! mapListener) google.maps.event.removeListener(mapListener);

    mapListener = google.maps.event.addListener(map, 'click', function(e) {
        tools.addPoint(e.latLng);
    });
}

newPolyline = function() {
    if ( !! mapListener) google.maps.event.removeListener(mapListener);

    tools.createPolyline();
    mapListener = google.maps.event.addListener(map, 'click', function(e) {
        tools.addPoint(e.latLng);
    });
}

newPolygon = function() {
    if ( !! mapListener) google.maps.event.removeListener(mapListener);

    tools.createPolygon();
    mapListener = google.maps.event.addListener(map, 'click', function(e) {
        tools.addPoint(e.latLng);
    });
}

var tools = {
    polyMarkers: [],
    polyLines: [],
    polyLine: null,
    // ...

    // mapListener: null,
    // tools: function(option) {
    //     if ( !! this.mapListener) google.maps.event.removeListener(this.mapListener);
    //     this.mapListener = google.maps.event.addListener(map, 'click', function(e) {
    //         option(e.latLng);
    //     });
    // },
    // and so on

编辑我得到了预期的功能,添加到工具中:

mapListener: null,

initFeature: function(type, aspect) {
    if ( !! this.mapListener) google.maps.event.removeListener(this.mapListener);

    if (aspect) this[aspect]();

    this.mapListener = google.maps.event.addListener(map, 'click', function(e) {
        tools[type](e.latLng);
    });
},

呼叫:

tools.initFeature(type, aspect);

1 个答案:

答案 0 :(得分:1)

如果我得到你想要做的事情,也许有一个构建器功能会有所帮助,这样的事情可以处理你的大多数情况。

function MakeNew(act1, act2) {

    return function() {

        if ( !! mapListener) google.maps.event.removeListener(mapListener);

        if ( act2 ) tools[act2]();

        mapListener = google.maps.event.addListener(map, 'click', function(e) {
            tools[act1](e.latLng);
        });
    };
};


dropMarker = MakeNew('createMarker');
newPolygon = MakeNew('addPoint', 'createPolygon');
createPolygon = MakeNew('addPoint', 'createPolyline');