簡體   English   中英

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

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

我在Leaflet和Backbone.js之間的集成有問題。 我采取了一個在線示例( 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();

現在,問題是當我嘗試使用以下方法更新模型中標記的集合時:

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

(節點是我要添加的自定義標記,視圖未更新,並且標記未顯示在地圖上。我在做什么錯?謝謝!

也許你應該把這個放在你看來

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

這也會更新您的視圖和地圖

謝謝您的幫助。 顯然,我通過添加以下內容解決了更新問題:

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

函數在哪里:

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

添加數據后,我還必須在模型上觸發事件“添加”:

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

現在的問題是,地圖無法使用標記實時刷新。 有人用傳單成功做到了嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM