转换为匿名函数

时间:2015-10-26 11:52:17

标签: jquery anonymous-function

我想将this example code转换为函数。我想这样做,因为我在同一页面上有2个输入字段,必须使用此自动完成功能。我可以像以前那样用旧的方式做到这一点,但我想了解一下这种类型的编程。这就是我现在所拥有的:

var Lookup = {
    init: function(field) {
        this.field = field;
        this.autocomplete = null;
        this.autocomplete = new google.maps.places.Autocomplete((document.getElementById(this.field)), {
            types: ['geocode']
        });
        this.autocomplete.addListener('place_changed', this.fillInAddress());
    },
    geolocate: function() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var geolocation = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
                var circle = new google.maps.Circle({
                    center: geolocation,
                    radius: position.coords.accuracy
                });
                this.autocomplete.setBounds(circle.getBounds());
            });
        }
    },
    fillInAddress: function() {
        var place = this.autocomplete.getPlace();
        console.log(place); 
    }
}

我执行以下操作:

$(document).ready(function () {
    Lookup.init('location_from');
    Lookup.init('location_to');
});

一切正常,两个字段都有自动完成功能。但是当我选择一个地址时,我收到了这个错误:

  

未捕获的TypeError:无法读取未定义的属性“apply”

这发生在fillInAddress函数中。进行AJAX调用(请求该地点的额外细节),但随后停止。谁能告诉我为什么会这样?

1 个答案:

答案 0 :(得分:1)

我想你想为这个任务创建一个jQuery插件:

$.fn.extend({
    geocode: function () {
        return this.each(function () {
            var ac = new google.maps.places.Autocomplete(this), {
                types: ['geocode']
            });
            ac.addListener('place_changed', function () {
                var place = ac.getPlace();
                console.log(place);
                // ... etc ...
            });
        });
    }
});

$('#location_from, #location_to').geocode();