BaseWidget.js 14.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
///////////////////////////////////////////////////////////////////////////
// Copyright © 2014 Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////

define([
  'dojo/_base/declare',
  'dojo/_base/lang',
  'dojo/_base/array',
  'dojo/topic',
  "dojo/Deferred",
  "dojo/cookie",
  'dijit/_WidgetBase',
  'dijit/_TemplatedMixin'
], function(declare, lang, array, topic, Deferred, dojoCookie, _WidgetBase, _TemplatedMixin){
  var clazz = declare([_WidgetBase, _TemplatedMixin], {
    //type: String
    //    the value shoulb be widget
    type: 'widget',

    /****these properties can be configured (be overrided) in app's config.json*****/
    //id: String
    //    the unique id of the widget, if not set in the config file,
    //    ConfigManager will generate one
    id: undefined,

    //label: String
    //    the display name of the widget
    label: undefined,

    //icon: String
    //    the uri of the icon, use images/icon.png if not set
    icon: undefined,

    //uir: String
    //    used in the config.json to locate where the widget is
    uri: undefined,

    /*======
      //left: int
      //top: int
      //right: int
      //bottom: int
      //width: int
      //height: int
    ======*/
    //    preload widget should config position property if it's not in group.
    //    the meaning of the property is the same as of the CSS
    position: {},
    
    //config: Object|String
    //    config info in config.json, url or json object
    //    if url is configured in the config.json, json file is parsed and stored in this property
    config: undefined,

    //defaultState: Boolean
    openAtStart: false,
    
    /***************************************************************/

    /*********these properties is set by the framework**************/
    //map: esri/Map|esri3d/Map
    map: null,
    //MapView: esri/Map|esri3d/Map
    view: null,

    //appConfig: Object
    //    the app's config.json
    appConfig: null,

    //folderUrl: String
    //    the folder url of the widget
    folderUrl: null,

    //state: String
    //    the current state of the widget, the available states are:
    //    opened, closed, active(TBD, when widget get focus)
    state: 'closed',

    //windowState: String
    //    the available states are normal, minimized, maximized
    windowState: 'normal',

    //started: boolean
    //    whether the widget has started
    started: false,

    //name: String
    //    the name is used to identify the widget. The name is the same as the widget folder name
    name: '',
    /***************************************************************/

    /*********these properties is set by the developer**************/

    //baseClass: String
    //    HTML CSS class name
    baseClass: null,

    //templateString: String
    //    widget UI part, the content of the file Widget.html will be set to this property
    templateString: '<div></div>',
    
    placeholder:'%s',
    
    /***************************************************************/

    constructor: function(){
      //listenWidgetNames: String[]
      //    builder uses this property to filter widgets. App will not use this property to
      //    filter messages.
      this.listenWidgetNames = [];

      //listenWidgetIds: String[]
      //    app use this property to filter data message, if not set, all message will be received.
      //    this property can be set in config.json
      this.listenWidgetIds = [];

      //About the communication between widgets:
      //  * Two widgets can communicate each other directly, or transferred by DataManager.
      //  * If you want to share data, please call *publishData*. the published data will
      //    be stored in DataManager.
      //  * If you want to read share data, you can override *onReceiveData* method. Whenever
      //    any widgt publishes data, this method will be invoked. (communication directly)
      //  * If you want to read the data that published before your widget loaded, you can call
      //    *fetchData* method and get data in *onReceiveData* method. If the data contains
      //    history data, it will be availble in *historyData* parameter.
      //      (transferred by DataManager)
      this.own(topic.subscribe('publishData', lang.hitch(this, this._onReceiveData)));
      this.own(topic.subscribe('dataFetched', lang.hitch(this, this._onReceiveData)));
      this.own(topic.subscribe('noData', lang.hitch(this, this._onNoData)));
    },

    onOpen: function(){
      // summary:
      //    this function will be called when widget is opened everytime.
      // description:
      //    state has been changed to "opened" when call this method.
      //    this function will be called in two cases:
      //      1. after widget's startup
      //      2. if widget is closed, use re-open the widget
    },

    onClose: function(){
      // summary:
      //    this function will be called when widget is closed.
      // description:
      //    state has been changed to "closed" when call this method.
    },

    onNormalize: function(){
      // summary:
      //    this function will be called when widget window is normalized.
      // description:
      //    windowState has been changed to "normal" when call this method.
    },

    onMinimize: function(){
      // summary:
      //    this function will be called when widget window is minimized.
      // description:
      //    windowState has been changed to "minimized" when call this method.
    },

    onMaximize: function(){
      // summary:
      //    this function will be called when widget window is maximized.
      // description:
      //    windowState has been changed to "maximized" when call this method.
    },


    onSignIn: function(credential){
      // summary:
      //    this function will be called after user sign in.

      /*jshint unused: false*/
    },

    onSignOut: function(){
      // summary:
      //    this function will be called after user sign in.
    },

    onPositionChange: function(position){
      //summary:
      //  this function will be called when position change,
      //  widget's position will be changed when layout change
      //  the position object may contain w/h/t/l/b/r
      this.position = position;
    },
    
    //lgf add 2017-09-19 
    getUserInfo:function(){
    	if(typeof this.user === 'undefined'){
    		topic.publish("app/userinfo", this);
    	}
    	return this.user;
    },
    
    //lgf add 2017-07-20 
    getMapServerUrl:function(url){
    	if(url.indexOf("http://") != -1)
    		return url;
    	else
    		return "http://"+this.appConfig.hosts.mapserverhost+"/"+url;
    },
    
    //lgf add 2017-05-06
    //lgf update 2017-07-20 
    getRequestUrlByLabel:function(label){
    	var requestUrl = "";
    	array.forEach(this.appConfig["requests"], lang.hitch(this, function (item) {
            if (item["label"] == label) {
            	if(item.port)
            		requestUrl = item.port+ "/" + item["path"];
            	else
            		requestUrl = "http://" +this.appConfig.hosts.serverhost+ "/" + item["path"];
            }
        }));
    	return requestUrl;
    },
    
    //lgf add 2017-05-06
    //lgf update 2017-07-19 
    requestDefaultByUrlAndParam:function(url, args, options){
    	var def = new Deferred();
    	var msg = -1;
    	var tip = undefined;
    	var shade = 0.01;
    	var icon =  16;
    	var type  = "POST";
    	var token = null;
    	if(options){
    		tip = options.tip || tip;
    		shade = options.shade || shade;
    		icon = options.icon || icon;
    		type = options.type || type;
    		token = options.token || token;
    	}
    	
    	if(!url || url == ""){
    		console.log("请检查请求路径");
    		return;
    	}
    	
    	if(layer){
    		if(typeof tip === "string"){
    			msg = layer.msg(tip, {icon: icon,shade: shade});
    		}
    	}
    	var headers=null;
    	//token
    	if(token){
    		headers = {"token":token};
    	}else{
    		headers = {"content-type": "application/json"};
    	}
    	if($){
    		var settings = {
				  "async": true,
				  "url": url,
				  "method": type,
				  "dataType":'json',  
				  "headers":headers,
				  "contentType":"application/json",
				  "processData": false,
				  "data": args,
				  success:function(result,textStatus){ 
					  def.resolve(result);
		    		  if(layer){layer.close(msg);}
				  }, 
				  error:function(error){ 
					  def.reject(error);
					  if(layer){layer.close(msg);}
				  } 
				};

    		// ajax 向后台发送请求
    		$.ajax(settings); 
    	}
    	return def;
    },
    
    //lgf add 2017-05-023
    //lgf update 2017-07-19 
    requestMapServerByUrlAndParam:function(url, args, options){
    	var def = new Deferred();
    	var msg = -1;
    	var tip = undefined;
    	var shade = 0.01;
    	var icon =  16;
    	var type  = "POST";
    	if(options){
    		tip = options.tip || tip;
    		shade = options.shade || shade;
    		icon = options.icon || icon;
    		type = options.tip || type;
    	}
    	
    	if(!url || url == ""){
    		console.log("请检查请求路径");
    		return;
    	}
    	
    	if(layer){
    		if(typeof tip === "string"){
    			msg = layer.msg(tip, {icon: icon,shade: shade});
    		}
    	}
    	if($){
    		if(type == "POST"){
    			$.post(url,args,lang.hitch(this, function(result){
        			def.resolve(result);
        			if(layer){layer.close(msg);}
    			})).error(lang.hitch(this, function(error) { 
    				def.reject(error);
    				if(layer){layer.close(msg);}
    			}));
    		}else if(type == "GET"){
    			$.get(url,args,lang.hitch(this, function(result){
        			def.resolve(result);
        			if(layer){layer.close(msg);}
    			})).error(lang.hitch(this, function(error) { 
    				def.reject(error);
    				if(layer){layer.close(msg);}
    			}));
    		}else{
    			console.log("不支持此类型的请求:"+type);
    		}
    	}
    	return def;
    },
    
    //lgf add 2017-07-20
    //lgf update 2017-08-07
    onContentHide:function(selector){
    	selector = selector || '.'+this.baseClass;
    	$(selector).css('left','0px');
    	$(selector).fadeOut();
//    	this.onContentAnimate(selector, '0px', {
//    		field:'left',
//    		params:{'left':'-270px'},
//    		speed:500,
//    		callback:lang.hitch(this, function(){
//    			$(selector).hide();
//    		})
//    	});
    },
    
    //lgf add 2017-07-20
    //lgf update 2017-08-07
    onContentShow:function(selector){
    	selector = selector || '.'+this.baseClass;
    	$(selector).css('left','0px');
    	$(selector).fadeIn();
//    	this.onContentAnimate(selector, '-270px', {
//    		field:'left',
//    		params:{'left':'0px'},
//    		speed:500
//    	});
    },
    
    //lgf add 2017-07-20
    onContentAnimate:function(selector, compare_value, options){
    	var value = $(selector).css(options.field);
    	if(value == compare_value){
    		$(selector).animate(options.params , options.speed, options.callback);
    	}
    },
    
    setTemplateString:function(templateString){
    	this.templateString = templateString;
    },

    setMap: function(map){
      this.map = map;
    },
    
    setView: function(view){
      this.view = view;
    },

    setState: function(state){
      this.state = state;
    },

    setWindowState: function(state){
      this.windowState = state;
    },

    resize: function(){
    },

    //these three methods are used by builder.
    onConfigChanged: function(config){
      /*jshint unused: false*/
    },

    onAppConfigChanged: function(appConfig, reason, changedData){
      /*jshint unused: false*/
    },

    onAction: function(action, data){
      /*jshint unused: false*/
    },

    publishData: function(data, keepHistory){
      //if set keepHistory = true, all published data will be stored in datamanager,
      //this may cause memory problem.
      if(typeof keepHistory === 'undefined'){
        //by default, we don't keep the history of the data.
        keepHistory = false;
      }
      topic.publish('publishData', this.name, this.id, data, keepHistory);
    },

    fetchData: function(widgetId){
      //widgetId, the widget id that you want to read data. it is optional.
      if(widgetId){
        topic.publish('fetchData', widgetId);
      }else{
        if(this.listenWidgetIds.length !== 0){
          array.forEach(this.listenWidgetIds, function(widgetId){
            topic.publish('fetchData', widgetId);
          }, this);
        }else{
          topic.publish('fetchData');
        }
      }
    },

    fetchDataByName: function(widgetName){
      //widgetId, the widget name that you want to read data. it is required.
      var widgets = this.widgetManager.getWidgetsByName(widgetName);

      array.forEach(widgets, function(widget){
        this.fetchData(widget.id);
      }, this);
    },

    _onReceiveData: function(name, widgetId, data, historyData){
      //the data is what I published
      if(widgetId === this.id){
        return;
      }
      //I am not interested in the the widget id
      if(this.listenWidgetIds.length !== 0 && this.listenWidgetIds.indexOf(widgetId) < 0){
        return;
      }
      this.onReceiveData(name, widgetId, data, historyData);
    },

    onReceiveData: function(name, widgetId, data, historyData){
      /* jshint unused: false */
      // console.log('onReceiveData: ' + name + ',' + widgetId + ',data:' + data);

      //About historyData:
      //If you call fetchData and the widget that published the data with "keepHistory"
      //this historyData will be availble, or the historyData will be undefined.
    },

    _onNoData: function(name, widgetId){
      /*jshint unused: false*/
      if(this.listenWidgetIds.length !== 0 && this.listenWidgetIds.indexOf(widgetId) < 0){
        return;
      }
      this.onNoData(name, widgetId);
    },

    onNoData: function(name, widgetId){
      /*jshint unused: false*/
    },

    httpIndexOf: function (url) {
        if (url){
            url = url.replace(new RegExp(/\\|\//g), "/");
            if ( url.indexOf("http://") == -1) {
                return "http://" + url;
            }
            return url;
        }
        return '';
    }
  });
  return clazz;
});