KnockoutJS 中的 ViewModel 无法访问全局变量

Posted

技术标签:

【中文标题】KnockoutJS 中的 ViewModel 无法访问全局变量【英文标题】:Global variable not accessible to ViewModel in KnockoutJS 【发布时间】:2018-03-21 10:45:12 【问题描述】:

我正在使用 KnockoutJS 库开发一个简单的 Google 地图应用程序 - 或者至少它在概念上看起来足够简单。 在阅读了 KnockoutJS 并编写了一些示例之后,我将最初的部分放在一起。到目前为止的 html 只是地图,我的目标是在克服第一个障碍后立即填充列表。障碍在于javascript。以下是参考代码:

"use strict";

var map;
var center;
var defaultBounds;
var placesServices;

//LocationObject created to hold data for locations generated from google.places.nearbySearch
var LocationObject = function(data)

    this.position = data.geometry.location;
    this.lat = data.geometry.location.lat;
    this.lng = data.geometry.location.lng;
    this.name = data.name;
    this.placeID = data.place_id;
    this.rating = data.rating;
    this.types = data.types;
    this.linkToPhoto = data.html_attributions;

;



function initMap()

    map = new google.maps.Map(document.getElementById('map'), 
        center: center,
        zoom: 17,
        mapTypeId: 'satellite',
        draggable: true, 
        zoomControl: false, 
        scrollwheel: true, 
        disableDoubleClickZoom: true
    );

    defaultBounds = new google.maps.LatLngBounds(
        new google.maps.LatLng(47.614217, -122.317981),new google.maps.LatLng(47.612975, -122.316291));
    map.fitBounds(defaultBounds);

    placesServices = new google.maps.places.PlacesService(map);




    //ViewModel created to observe changes on the map
var MapViewModel = function()
    var self = this;

    self.testarr = ko.observableArray([
         firstName: 'Bert', lastName: 'Bertington' ,
         firstName: 'Charles', lastName: 'Charlesforth' ,
         firstName: 'Denise', lastName: 'Dentiste' 
    ]);

    self.locations = ko.observableArray([]);
    self.markers = [];

    this.getNearbyLocations = function()
        if(placesServices === undefined)
            placesServices = new google.maps.places.PlacesService(map);
        

        var request = 
            location: center,
            radius: getBoundsRadius(defaultBounds),
            type: ['establishment']
        ;

        placesServices.nearbySearch(request, function(results, status) 
            if (status === google.maps.places.PlacesServiceStatus.OK) 
                for (var i = 0; i <= 18; i++) 
                    var marker = new google.maps.Marker(
                        map: map,
                        position: results[i].geometry.location,
                        animation: google.maps.Animation.DROP
                    );
                    self.locations.push(new LocationObject(results[i]));
                    self.markers.push(marker);
                
             else
                alert("We were not able to find any nearby locations in this Neighbourhood.");
            
        );
    ;

    this.init = function()

        self.getNearbyLocations();

    ;
;


var myMapViewModel = new MapViewModel();
myMapViewModel.init();
ko.applyBindings(myMapViewModel);   



/* Utility Functions */
function getBoundsRadius(bounds)....

错误是:

Uncaught ReferenceError: google is not defined
at MapViewModel.getNearbyLocations

我不明白为什么它在这里没有被识别,当地图本身首先加载没有问题但在这里它被挂断了。

这是供参考的html,但那里应该没有问题:

<!DOCTYPE html>
<html lang="en">
  <head>
   <!-- Required meta tags -->
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

   <!-- Per Google guideline scheduled for the M65 release, css has been moved to an importer -->
   <link rel="import" href="importer.htm"></link>

   <!-- Bootstrap CSS -->
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">


  </head>
  <body>
   <div class="container-fluid">
    <div class="row">
        <div class="col-xs-12 col-md-4">
            <!-- List goes in this column. -->

            </div>
        </div>
        <div class="col-xs-12 col-md-8">
            <!-- Map goes into this column. -->
            <div id="map" style="width:100%;height:100vh;"></div>
        </div>
      </div>
     </div>

<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<!-- Optional JavaScript -->
<script src="js/knockout.js" ></script>
<script src="js/app.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC-1EdIyUOb74oGG_mEoPvJTAGCSJvSQms&callback=initMap&libraries=places"></script>
 </body>

【问题讨论】:

尝试在app.js之前添加地图脚本引用 您可能还想查看this question的答案 【参考方案1】:

我还认为错误是因为您的 app.js 在地图脚本之前被调用。但我尝试更改它,同样的错误,我还尝试删除 async 参数(如 user3297291 的评论所建议),仍然是同样的错误。理论上是should have worked.

但这有效 - 将 app.js 代码的最后 3 行包装在 ready() 函数中:

$(document).ready(function()
    var myMapViewModel = new MapViewModel();
    myMapViewModel.init();
    ko.applyBindings(myMapViewModel); 
);

【讨论】:

是的,我昨天也测试了所有这些替代方案 - 结果与您发现的相同。此外,由于地图正在加载并存储在全局声明的变量中,我认为它应该是可访问的。有一次,我尝试了一种实现,将变量传递给相应的函数,但结果相同。今晚我将添加 jquery 选项,并在确认后批准。 我最终不得不在超时中包装它,但这让我足够接近 - 谢谢!

以上是关于KnockoutJS 中的 ViewModel 无法访问全局变量的主要内容,如果未能解决你的问题,请参考以下文章

knockoutjs如何动态加载外部的file作为component中的template数据源

knockoutjs如何动态加载外部的file作为component中的template数据源

有没有办法异步初始化 Viewmodel (KnockoutJS)

KnockoutJS,ajax 调用后更新 ViewModel

如何在 KnockoutJS 中访问 ViewModel 之外的 observable?

knockoutjs 打破数组中的循环