前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >高质量编码-基于观察者模式的事件图层

高质量编码-基于观察者模式的事件图层

原创
作者头像
MiaoGIS
修改2019-05-23 17:55:36
4100
修改2019-05-23 17:55:36
举报
文章被收录于专栏:Python in AI-IOT

怎么做到,地图上的要素绑定到特定的事件接口上,随着时间增加要素或删除要素,或更新要素的符号,属性,我们使用Backbone .js实现观察者模式来完成此功能特性。

Backbone是依赖于JQueryUnderscore的js库,和Angular,React,Vue一样,是一个Web前端MVC框架。Backbone中用Backbone.Events来实现事件订阅,Backbone.Model来表示模型,Backbone.Collection来表示集合,Backbone.View来表示视图。其中Backbone.Model和Backbone.Collection继承自Backbone.Events,Backbone.Model可以绑定change事件,Backbone.Collection可以绑定add,remove事件。同时继承自Backbone.Events的对象之间可以互相监听对方的事件。

事件图层其实就是利用了Backbone.Collection的addremove,以及Backbone.Model的change事件,前者可以指定后者为集合中的元素类型。只需要监听集合,当集合中有Model实例add时,地图上创建对应表示的要素图形,当发现有Model实例remove,地图上移除对应表示的要素图形,当Model实例属性change时,根据变化后的属性更新地图上对应的要素图形。

代码如下:

代码语言:javascript
复制
function initPayEvent() {
    window.payLayer = new GraphicsLayer({
        'id': 'payLayer'
    });
    map.addLayer(payLayer);
    window.ModelPayEvent = Backbone.Model.extend({
        'idAttribute': 'id'
    });
    window.ColPayEvent = Backbone.Collection.extend({
        'model': ModelPayEvent
    });
    window.colPayEvent = new ColPayEvent();

    window.colPayEvent.on('add', function (item) {
        console.log('pay added');
        var infoTemplate = new InfoTemplate("title", "content");
        var pictureMarkerSymbol = new PictureMarkerSymbol(item.attributes['avatar'], 25, 25);
        var regionLayer = toGraphicsLayer(dictFeatureLayer["小区"]);

        var regionGraphic = _.find(regionLayer.graphics, function (item2) {
            return parseKMLAttributes_region(item2.attributes)['FID'] == item.get('region');
        });
      

        var graphic = new Graphic(regionGraphic.geometry.getCentroid(), pictureMarkerSymbol, item.attributes, infoTemplate);
        payLayer.add(graphic);
        console.log(item);


        var payAlertTemplate = _.template($('[data-role="payAlertTemplate"]').html());
        $('.payAlert>div:gt(1)').remove();
        var regionName = parseKMLAttributes_region(regionGraphic.attributes)['name'];
        $('.payAlert').prepend($(payAlertTemplate(_.extend(item.attributes, {
            'regionName': regionName
        }))));
    });
    window.colPayEvent.on('remove', function (item) {

        var graphic = _.find(payLayer.graphics, function (item2) {
            return item2['attributes']['region'] == item.attributes['region']
        });
        payLayer.remove(graphic)
        console.log('pay removed');
        console.log(item);

    });

这里使用一个GraphicsLayer来管理所有的要素图形,Model是根据idAttribute指定的字段名称来标示唯一。根据每个缴费用户的所在小区ID来查到小区图层里对应的graphic,通过regionGraphic.geometry.getCentroid()将用户微信头像显示在小区中心点。另外由于使用了KMLLayer,要素的真正属性字典必须通过解析对应的description获得。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档