1

자바가 제 첫 번째 언어가 아니며 잘 알고 있습니다. 기능상의 멋진 물건, 많은 물건이 아닙니다.전역 변수 감소 및 기능 흐름 유지

누구나 다음 시나리오를 처리하기위한 옵션을 제안 할 수 있는지보고 싶습니다.

function postcodeEntry(destination,postcode) { 
    "use strict"; 
    document.getElementById('googlemappostcode').innerHTML = <?php if ($_GET['page']==="fun") echo "<div id=\"map\"></div>' + ";?>'<form id="postcodeEntry" method="post" action="/" onsubmit="calcRoute(\'driving\',this.postcode.value,' + destination.hb + ',' + destination.ib + ',\'' + postcode + '\');return false;">' 
     + '<h2>Get directions</h2>' 
     + '<fieldset>' 
     + '<input type="hidden" name="action" value="gmap-directions" />' 
     + '<p class="where"><a href="/contact/" onclick="geoLoc();return false;">Where am I?</a></p>' 
     + '<label for="postcode">Enter your postcode for directions</label>' 
     + '<input type="text" name="postcode" id="postcode" onfocus="checkthis(this,\'Your Postcode/Address:\')" onblur="checkthis(this,\'Your Postcode/Address:\')" value="Your Postcode/Address:" />' 
     + '<input type="submit" name="submitTravelType" value="Driving" id="gms_driving" onclick="calcRoute(\'driving\',document.getElementById(\'postcode\').value,' + destination.hb + ',' + destination.ib + ',\'' + postcode + '\');return false;" />' 
     + '<input type="submit" name="submitTravelType" value="Walking" id="gms_walking" onclick="calcRoute(\'walking\',document.getElementById(\'postcode\').value,' + destination.hb + ',' + destination.ib + ',\'' + postcode + '\');return false;" />' 
     + '<input type="submit" name="submitTravelType" value="Public Transport" id="gms_transit" onclick="calcRoute(\'transit\',document.getElementById(\'postcode\').value,' + destination.hb + ',' + destination.ib + ',\'' + postcode + '\');return false;" />' 
     + '<input type="submit" name="submitTravelType" value="Cycling" id="gms_bicycling" onclick="calcRoute(\'bicycling\',document.getElementById(\'postcode\').value,' + destination.hb + ',' + destination.ib + ',\'' + postcode + '\');return false;" />' 
     + '</fieldset>' 
     + '</form>' 
     + '<div id="directions"></div>'; 
} 

function initialize() { 
    "use strict"; 
    var contentString, destination, el, entryPanoId, i, image, infowindow, links, mapOptions, panoId, panoOptions, radius, shadow, shape; 
    /* Destination becomes a four part array. 1st being lat, 2nd being long, 3rd being a google maps latlng and the 4th being postcode */ 
    destination = [<?php echo $venue['latlong']?>]; 
    destination[2] = new google.maps.LatLng(destination[0], destination[1]); 
    destination[3] = '<?php echo $venue['postcode']?>'; 
    postcodeEntry(destination[2], destination[3]); 
    directionsService = new google.maps.DirectionsService(); 
    directionsDisplay = new google.maps.DirectionsRenderer(); 
    trafficLayer = new google.maps.TrafficLayer(); 
    streetviewService = new google.maps.StreetViewService(); 
    ... 

초기화 기능이 호출되면 비트가되어 맵을 잘 만듭니다. 우편 번호/위치 항목이 완벽하게 작동합니다. 사실 그것은 모든 문제없이 작동합니다.

제 질문은 일부 정보가 우편 번호 양식에 저장되어 있기 때문에 해당 양식의 반환은 geoLoc 또는 calcRoute 기능으로 이동합니다. 물론 이것은 초기화 기능에서 설정 한 것과의 접촉을 잃는 것을 의미합니다.

이것은 표시된 스크립트 세그먼트의 모든 항목을 포함하여 많은 수의 전역 변수를 사용해야 함을 의미합니다.

나는 언어에 대해 더 많이 배우고 그것의 사용에 능숙 해지고있다. 결과적으로, (나는 순수한 완고함에서 벗어나서) 전역을 아무도 (가능한 경우) 또는 가능한 한 적게 줄이기 위해 노력하고 싶습니다.

해결 방법이 있습니까? 나는 자바 스크립트 객체에 대해 많이 알지는 못하지만 모든 시간을 배우기 때문에 어떻게 초기화 함수를 다른 객체를 포함하는 객체로 바꿀 수 있습니까? (현재 자바 스크립트 객체에 대해 거의 알지 못하는 것을 고려하면 실제로 완전히 미칠 수도 있습니다.)

답변

1

이런 식으로해야 할 때 일반적으로 생성자/프로토 타입 (적절한 용어가 무엇인지 잊어 버렸습니다)을 사용합니다.

예 :

var obj = new initialise(); 

및과 같이 대중 함수를 호출 :

// This is the constructor 
function initialise(){ 
    // Add various settings values here 
    this.foo = 'bar'; 
} 

// These are some publicly accessible methods 
initialise.prototype = { 
    alertFoo: function(){ 
     alert(this.foo); // The value of foo can be accessed via this.foo 
    }, 

    consolelogFoo: function(){ 
     console.log(this.foo); 
    } 
} 

당신은 다음과 같이, 초기화 객체를 생성 할 수 있습니다

obj.alertFoo(); 

이이 방법의 단지 간단한 예입니다. 코드를 직접 구현해야하지만이 작업을 수행하는 방법에 대한 간단한 아이디어를 얻으려면 여기에 내가 한 것입니다.

function initialize(options){ // options can be an object with stuff from data-* attributes 
    this.destination = {}; 
    this.destination.coords = new google.maps.LatLng(options.lat, options.long); 
    this.destination.postcode = options.postcode; 
    this.directionsService = new google.maps.DirectionsService(); 
    this.directionsDisplay = new google.maps.DirectionsRenderer(); 
    this.trafficLayer = new google.maps.TrafficLayer(); 
    this.streetviewService = new google.maps.StreetViewService(); 
    .... 
} 

initialize.prototype = { 
    geoLoc: function(){ 
     // do stuff 
    }, 

    calcRoute: function(){ 
     // do stuff 
    } 
} 

이렇게하면 예를 들어 값을 업데이트해야 할 때. 대상 좌표의 경우 public 메서드에 this.destination.coords 속성을 업데이트하기 만하면됩니다.

HTML 코드는 가능한 한 JS를 사용하여 HTML 코드를 삽입하지 않는 것이 좋습니다. 그것은 단지 좋은 습관이 아닙니다.

또한 JS 코드에 PHP 코드를 혼합하는 것을 권장하지 않습니다. JS 코드를 PHP에서 제공해야 할 때 별도로 보관하고 data- * 속성을 사용하는 것이 좋습니다.

이 정보가 도움이되기를 바랍니다.

편집 : 양식 이벤트를 제출 핸들러하는 방법에 대한 귀하의 질문에 대답, 당신은 같은 것을 할 수 있습니다 그것에 대해

function initialize(){ 
    .... 
    this.form = document.form1; // Assuming you have a form called form1 
    this.init(); 
} 

initialize.prototype = { 
    init: function(){ // I usually use this approach for attaching event handlers and other stuff so as keep the constructor clean, and separate the concerns 
     this.form.onsubmit = this.formHandler; 
    }, 
    .... 
    formHandler: function(){ // This is the form handler 
     alert(this.textField1.value); // Assuming form1 has a field called textField1 
     return false; // This will prevent the form from being submitted via traditional page POST request 
    }, 
    .... 
}; 
+0

감사합니다 :) 내가 아주 의도적으로 HTML 코드를 생성하는 JS를 사용하여 실제로 나는 때문에 자바 스크립트가 꺼져 있거나 사용 가능하지 않을 때 다른 옵션을 사용할 수 있다는 의미의 다른 부분이 있습니다. 사용 가능한 경우 js의 대화식 기능으로 대체됩니다. 그렇게하는 것은 의식적인 결정입니다. PHP에 관해서는 개인적인 것 같아요. 한 가지 질문입니다. 양식이 게시해야하는 기능을 어떻게 처리합니까? – Rafe

+0

방금 ​​내 대답에 몇 가지 추가 예제를 추가했습니다. 희망이 도움이됩니다. –

+0

이것은 갈 길과 같습니다. 어제 무거운 학습 곡선 후에 기능의 절반 만 변환했습니다. 나는 몇몇 조회가있다 그러나 나가 응답을 나 자신 찾아 낼 수없는 경우에 나는 다른 질문을 위해 그 (것)들을 저장할 것이다. 고마워요 :) – Rafe