简体   繁体   English

Leaflet + Backbone.js:如何在模型集合更新中更新视图?

[英]Leaflet + Backbone.js: how to update the view on model collection update?

I have a problem with the integration between Leaflet and Backbone.js. 我在Leaflet和Backbone.js之间的集成有问题。 I took a sample I found online ( http://jsfiddle.net/dPqQy/ ) that has the following View and Model for the Map: 我采取了一个在线示例( http://jsfiddle.net/dPqQy/ ),该示例具有以下针对地图的视图和模型:

App.Views.MapView = Backbone.View.extend({
id:"map",
render: function() {
    //render map element
    var map = this.map =  L.map(this.$el.attr('id'))
    .setView([this.model.get('centerLon'),  this.model.get('centerLat') ], 13)
    .addLayer(L.tileLayer(this.model.get('layerUrl'), { maxZoom: 18 }));

    //render each marker
    this.markerViews = this.model.get('markers').map(function(marker) {
        return new App.Views.MarkerView({model:marker, map:map}).render();
    });
    }
});

var map = new App.Models.Map({
    centerLon: 51.505,
    centerLat: -0.09,
    layerUrl:      'http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png',
    markers: new App.Collections.Markers([
        {id:1, latitude:-0.09, longitude:51.505},
        {id:2, latitude:-0.092, longitude:51.503},
        {id:3, latitude:-0.086, longitude:51.506}
    ])
 });

var mapView = new App.Views.MapView({model:map});
mapView.render();

Now, the problem is that when I try to update the marker's collection in the model with: 现在,问题是当我尝试使用以下方法更新模型中标记的集合时:

map.get('markers').add(node);

(node is a custom marker that I want to add, the View doesn't get updated and the marker doesn't show in the map. What am I doing wrong? Thanks! (节点是我要添加的自定义标记,视图未更新,并且标记未显示在地图上。我在做什么错?谢谢!

probably you should put this in your view 也许你应该把这个放在你看来

initialize: function () {
   this.listenTo(this.model, 'add', this.render);
},

this will update your view and map as well 这也会更新您的视图和地图

Thanks for the help. 谢谢您的帮助。 Apparently I fixed the update issue by adding this: 显然,我通过添加以下内容解决了更新问题:

    initialize: function() {
        this.listenTo(this.model, 'add', this.addMarker);
    }

Where the function is: 函数在哪里:

    addMarker: function() {

        var markers = this.model.get('markers');
        var markersLength = this.model.get('markers').length;
        var markerView = new App.Views.MarkerView({model: markers.models[markersLength-1], map:this.map});
        this.el.appendChild(markerView.render().el);
    }

I also had to trigger the event 'add' on the model after I add the data: 添加数据后,我还必须在模型上触发事件“添加”:

    map.get('markers').add(node);
    map.trigger('add'); 

Now, the problem is that the map doesn't refresh in real-time with the markers. 现在的问题是,地图无法使用标记实时刷新。 Has anyone been successful in doing that with leaflet? 有人用传单成功做到了吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM