减少全局变量并保持功能流 [英] Reducing global variables and maintaining function flow

查看:142
本文介绍了减少全局变量并保持功能流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript不是我的第一选择语言,也不是我所熟悉的。
功能性东西很好,对象不多。



 函数postcodeEntry(目的地,邮政编码) ){
使用严格;
document.getElementById('googlemappostcode')。innerHTML =<?php if($ _GET ['page'] ===fun)echo< div id = \map \> ;< / div>'+;?>'< form id =postcodeEntrymethod =postaction =/onsubmit =calcRoute(\'driving\',this.postcode.value ,'+ destination.hb +','+ destination.ib +',\'+ postcode +'\'); return false;>'
+'< h2>获取路线< / h2>'
+'< fieldset>'
+'< input type =hiddenname =actionvalue =gmap-directions/>'
+ '< p class =where>< a href =/ contact /onclick =geoLoc(); return false;>我在哪?< / a>< / p>
+'< label for =postcode>输入您的邮政编码寻找路线< / label>'
+'< input type =textname =postcodeid =postcodeonfocus =checkthis(this,\'Your Postcode / Address:\')onblur =checkthis(this,\'You r'Postcode / Address:\')value =您的邮编/地址:/>'
+'< input type =submitname =submitTravelTypevalue =Drivingid = gms_drivingonclick =calcRoute(\'driving \',document.getElementById(\'postcode \')。value,'+ destination.hb +','+ destination.ib +',\'' +邮编+'\');返回false; />'
+'< input type =submitname =submitTravelTypevalue =Walkingid =gms_walkingonclick =calcRoute(\'walking\',document.getElementById \'postcode\')。value,'+ destination.hb +','+ destination.ib +',\''+邮编+'\'); return false; />'
+'< input type =submitname =submitTravelTypevalue =Public Transportid =gms_transitonclick =calcRoute(\'transit \',document.getElementById (\'postcode \')。value,'+ destination.hb +','+ destination.ib +',\''+邮编+'\'); return false; />'
+'< input type =submitname =submitTravelTypevalue =Cyclingid =gms_bicyclingonclick =calcRoute(\'bicycling\',document.getElementById \'postcode\')。value,'+ destination.hb +','+ destination.ib +',\''+邮编+'\'); return false; />'
+'< / fieldset>'
+'< / form>'
+'< div id =directions>< / div>' ;
}

函数initialize(){
use strict;
var contentString,destination,el,entryPanoId,i,image,infowindow,links,mapOptions,panoId,panoOptions,radius,shadow,shape;
/ * Destination成为四部分数组。第一个是拉特,第二个是长,第三个是谷歌地图latlng,第四个是邮编* /
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函数。这当然意味着我失去了与初始化函数中设置的任何东西的联系。

这意味着我必须使用相当多的全局变量,包括但不限于每个变量在所显示的脚本片段中的这些项目。



我正在尝试了解更多关于该语言的内容,并更加精通它的使用。因此,我希望(大多数情况下是纯粹的固执)尝试和减少全局(如果可能的话)或尽可能少。



有什么办法解决这个问题?我对javascript对象了解不多,但我一直在学习,所以不知何故将初始化函数转换为一个包含所有其他对象的对象? (考虑到我目前对JavaScript对象的了解有多少,可能实际上完全是疯了)

解决方案我通常会使用构造函数/原型(忘了什么是合适的名词)的方法,当我需要做这样的事情。



例如。

  //这是构造函数
函数initialise(){
//在这里添加各种设置值
this.foo ='bar';
}

//这些是一些可公开访问的方法
initialise.prototype = {
alertFoo:function(){
alert(this.foo) ; // foo的值可以通过this.foo访问
},

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




$ b你可以创建一个初始化对象,如下所示:

  var obj = new initialise(); 

并且像这样调用公共函数:

  obj.alertFoo(); 

这只是这种方法的一个简单例子。你需要自己实现你的代码,但是给你一个关于如何去做这件事的简要概念,这是我会做的。

  function initialize(options){//选项可以是一个包含data- *属性的对象
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
}
}

这样,当你需要更新例如。目标坐标,您只需告诉公共方法来更新this.destination.coords属性。



至于HTML代码,我建议您避免注入尽可能使用JS的HTML代码。这不是一个好习惯。



另外,我也不建议将PHP代码混合到您的JS代码中。最好将它们分开,并在需要从PHP提供JS代码时使用data- *属性。



我希望这有助于。



编辑:在回答关于如何处理表单提交事件的问题时,可以这样做:

 函数initialize(){
....
this.form = document.form1; //假设你有一个form1
this.init();


initialize.prototype = {
init:function(){//我通常使用这种方法来附加事件处理程序和其他东西,以保持构造器的清洁,并且分开关注
this.form.onsubmit = this.formHandler;
},
....
formHandler:function(){//这是表单处理函数
alert(this.textField1.value); //假设form1有一个名为textField1
的字段return false; //这将阻止通过传统页面POST请求
},
....
}提交表单;


Javascript is not my first language of choice, nor is it one I am all that well versed in. Functional stuff fine, objects, not so much.

I am looking to see if anyone can suggest options for dealing with the following scenario.

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

When the initialising function is called it does it's bit and makes the map fine. The postcode/location entry works perfectly. In fact it all works, no problems with that.

My question is being as some info is shot off to the postcode form, the return from that form goes to either the geoLoc or calcRoute functions. This of course means I lose contact with anything set up in the initialization function.

This means I have to use quite a number of global variables including but not limited to every one of those items in the shown script segment.

I am trying to learn more about the language and become more proficient in it's use. As a result, I would like (mostly out of pure stubbornness) to try and reduce the globals to none (if that's possible) or as few as possible.

Is there some way to solve this? I do not know much about javascript objects but I am learning all the time so somehow turn the initialize function into an object that then contains all the other objects? (Considering how little I know about javascript objects currently, that might actually be completely mad)

解决方案

I'd normally use a constructor/prototype (forgot what the proper term is) approach when I need to do something like this.

eg.

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

You can then create an initialise object, like so:

var obj = new initialise();

and call the public functions like so:

obj.alertFoo();

This is just a brief example of this approach. You'll need to implement your code yourself, but to give you a brief idea of how you can go about doing this, here's what I would have done.

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
    }
}

This way, when you need to update the value for eg. destination coordinates, you only have to tell your public method to update the this.destination.coords property.

As for the HTML code, I'd advise you to avoid injecting HTML code using JS as far as possible. It's just not a good practice.

Additionally, I also don't recommend mixing PHP code into your JS code. It's better to keep them separate, and use data-* attributes when you need to supply your JS code something from PHP.

I hope this helps.

EDIT: In answering your question about how to handler the form submit event, you can do something like this:

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
    },
    ....
};

这篇关于减少全局变量并保持功能流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆