amcharts get object on inited event - amcharts

amcharts v4 code
am4core.useTheme(am4themes_animated);
let chart = am4core.create("region-map", am4maps.MapChart);
let interfaceColors = new am4core.InterfaceColorSet();
// Set map definition
chart.geodata = am4geodata_worldLow;
// Set projection
chart.projection = new am4maps.projections.Mercator();
// Export
// Data for general and map use
let originCities = [
{
id: "london",
title: "London",
destinations: [
"vilnius",
"reykjavik",
"lisbon",
"moscow",
"belgrade",
"ljublana",
"madrid",
"stockholm",
"bern",
"kiev",
"new york",
],
latitude: 51.5002,
longitude: -0.1262,
scale: 1.5,
zoomLevel: 2.74,
zoomLongitude: -20.1341,
zoomLatitude: 49.1712,
},
];
let destinationCities = [
{
id: "brussels",
title: "Brussels",
latitude: 50.8371,
longitude: 4.3676,
},
{
id: "prague",
title: "Prague",
latitude: 50.0878,
longitude: 14.4205,
},
{
id: "athens",
title: "Athens",
latitude: 37.9792,
longitude: 23.7166,
},
{
id: "reykjavik",
title: "Reykjavik",
latitude: 64.1353,
longitude: -21.8952,
},
{
id: "dublin",
title: "Dublin",
latitude: 53.3441,
longitude: -6.2675,
},
{
id: "oslo",
title: "Oslo",
latitude: 59.9138,
longitude: 10.7387,
},
{
id: "lisbon",
title: "Lisbon",
latitude: 38.7072,
longitude: -9.1355,
},
{
id: "moscow",
title: "Moscow",
latitude: 55.7558,
longitude: 37.6176,
},
{
id: "belgrade",
title: "Belgrade",
latitude: 44.8048,
longitude: 20.4781,
},
{
id: "bratislava",
title: "Bratislava",
latitude: 48.2116,
longitude: 17.1547,
},
{
id: "ljublana",
title: "Ljubljana",
latitude: 46.0514,
longitude: 14.506,
},
{
id: "madrid",
title: "Madrid",
latitude: 40.4167,
longitude: -3.7033,
},
{
id: "stockholm",
title: "Stockholm",
latitude: 59.3328,
longitude: 18.0645,
},
{
id: "bern",
title: "Bern",
latitude: 46.948,
longitude: 7.4481,
},
{
id: "kiev",
title: "Kiev",
latitude: 50.4422,
longitude: 30.5367,
},
{
id: "paris",
title: "Paris",
latitude: 48.8567,
longitude: 2.351,
},
{
id: "new york",
title: "New York",
latitude: 40.43,
longitude: -74,
},
];
// Default to London view
//chart.homeGeoPoint = { "longitude": originCities[0].zoomLongitude, "latitude": originCities[0].zoomLatitude };
//chart.homeZoomLevel = originCities[0].zoomLevel;
let targetSVG =
"M9,0C4.029,0,0,4.029,0,9s4.029,9,9,9s9-4.029,9-9S13.971,0,9,0z M9,15.93 c-3.83,0-6.93-3.1-6.93-6.93S5.17,2.07,9,2.07s6.93,3.1,6.93,6.93S12.83,15.93,9,15.93 M12.5,9c0,1.933-1.567,3.5-3.5,3.5S5.5,10.933,5.5,9S7.067,5.5,9,5.5 S12.5,7.067,12.5,9z";
// Texts
let labelsContainer = chart.createChild(am4core.Container);
labelsContainer.isMeasured = false;
labelsContainer.x = 80;
labelsContainer.y = 27;
labelsContainer.layout = "horizontal";
labelsContainer.zIndex = 10;
// let plane = labelsContainer.createChild(am4core.Sprite);
// plane.scale = 0.15;
// plane.path = planeSVG;
// plane.fill = am4core.color("#cc0000");
// let title = labelsContainer.createChild(am4core.Label);
// title.text = "Flights from London";
// title.fill = am4core.color("#cc0000");
// title.fontSize = 20;
// title.valign = "middle";
// title.dy = 2;
// title.marginLeft = 15;
// let changeLink = chart.createChild(am4core.TextLink);
// changeLink.text = "Click to change origin city";
// changeLink.isMeasured = false;
// changeLink.events.on("hit", function () {
// if (currentOrigin == originImageSeries.dataItems.getIndex(0)) {
// showLines(originImageSeries.dataItems.getIndex(1));
// } else {
// showLines(originImageSeries.dataItems.getIndex(0));
// }
// });
// changeLink.x = 142;
// changeLink.y = 72;
// changeLink.fontSize = 13;
// The world
let worldPolygonSeries = chart.series.push(new am4maps.MapPolygonSeries());
worldPolygonSeries.useGeodata = true;
worldPolygonSeries.fillOpacity = 0.6;
worldPolygonSeries.exclude = ["AQ"];
// Origin series (big targets, London and Vilnius)
let originImageSeries = chart.series.push(new am4maps.MapImageSeries());
let originImageTemplate = originImageSeries.mapImages.template;
originImageTemplate.propertyFields.latitude = "latitude";
originImageTemplate.propertyFields.longitude = "longitude";
originImageTemplate.propertyFields.id = "id";
originImageTemplate.cursorOverStyle = am4core.MouseCursorStyle.pointer;
originImageTemplate.nonScaling = true;
originImageTemplate.tooltipText = "{title}";
originImageTemplate.setStateOnChildren = true;
originImageTemplate.states.create("hover");
originImageTemplate.horizontalCenter = "middle";
originImageTemplate.verticalCenter = "middle";
let originHitCircle = originImageTemplate.createChild(am4core.Circle);
originHitCircle.radius = 11;
originHitCircle.fill = interfaceColors.getFor("background");
let originTargetIcon = originImageTemplate.createChild(am4core.Sprite);
originTargetIcon.fill = interfaceColors.getFor("alternativeBackground");
originTargetIcon.strokeWidth = 0;
originTargetIcon.scale = 1.3;
originTargetIcon.horizontalCenter = "middle";
originTargetIcon.verticalCenter = "middle";
originTargetIcon.path = targetSVG;
let originHoverState = originTargetIcon.states.create("hover");
originHoverState.properties.fill = chart.colors.getIndex(1);
// when hit on city, change lines
originImageTemplate.events.on("hit", function (event) {
showLines(event.target.dataItem);
});
// destination series (small targets)
let destinationImageSeries = chart.series.push(
new am4maps.MapImageSeries()
);
let destinationImageTemplate = destinationImageSeries.mapImages.template;
destinationImageTemplate.nonScaling = true;
destinationImageTemplate.tooltipText = "{title}";
destinationImageTemplate.fill = interfaceColors.getFor(
"alternativeBackground"
);
destinationImageTemplate.setStateOnChildren = true;
destinationImageTemplate.states.create("hover");
destinationImageTemplate.propertyFields.latitude = "latitude";
destinationImageTemplate.propertyFields.longitude = "longitude";
destinationImageTemplate.propertyFields.id = "id";
let destinationHitCircle = destinationImageTemplate.createChild(
am4core.Circle
);
destinationHitCircle.radius = 7;
destinationHitCircle.fillOpacity = 1;
destinationHitCircle.fill = interfaceColors.getFor("background");
let destinationTargetIcon = destinationImageTemplate.createChild(
am4core.Sprite
);
destinationTargetIcon.scale = 0.7;
destinationTargetIcon.path = targetSVG;
destinationTargetIcon.horizontalCenter = "middle";
destinationTargetIcon.verticalCenter = "middle";
originImageSeries.data = originCities;
destinationImageSeries.data = destinationCities;
// Line series
let lineSeries = chart.series.push(new am4maps.MapLineSeries());
lineSeries.mapLines.template.line.strokeOpacity = 0.5;
lineSeries.mapLines.template.line.strokeDasharray = "1,1";
worldPolygonSeries.events.on("inited", function (ev) {
console.log(ev.target.dataItems.dataContext);
console.log(ev.target._dataItem.dataContext);
console.log(ev.target._dataFields);
});
lineSeries.events.on("inited", function (ev) {
console.log(ev.target.dataItems.dataContext);
console.log(ev.target._dataItem.dataContext);
console.log(ev.target._dataFields);
});
chart.events.on("ready", function (ev) {
showLines(originImageSeries.dataItems.getIndex(0));
});
I have amchart v4 code.Here i am trying to get the object when inited so that i can change the line color and make it dotted.But it is coming undefined.Please take a look how can i solve this.
I have tried logging above in 3 different ways but none working.
Do i need to make inited on charts or any series to get that data ?
Thanks

Related

How can I show the distance a polyline has covered while animating it in Mapbox GL JS?

I am using Mapbox GL JS to capture frame by frame video of the animation of a geoJson (similar to what is described here: https://docs.mapbox.com/mapbox-gl-js/example/animate-a-line/).
The strategy for encoding mapbox animations into mp4 here are described here:
https://github.com/mapbox/mapbox-gl-js/issues/5297 and https://github.com/mapbox/mapbox-gl-js/pull/10172 .
I would like to show the distance the polyline has covered as I draw each frame. I need the distance to be in the GL itself (as opposed to, for example, an HTML element on top of the canvas), since that's where I'm capturing the video from.
Can someone help describe a performant strategy for doing this to me?
Aside from tearing apart the Mapbox GL JS, why not simply try drawing directly onto the mapbox canvas?
In this example, there are two canvases, created identically.
With the second, there is another requestAnimationFrame loop that adds an overlay.
I've also shown how it can be recorded with MediaRecorder.
const canvas1 = document.getElementById('canvas1')
const canvas2 = document.getElementById('canvas2')
const video = document.getElementById('output')
const status = document.getElementById('status')
let x = 0 // Value to be displayed
const setupCanvas = (canvas) => {
canvas.height = 300
canvas.width = 300
const canvas1Ctx = canvas.getContext('2d')
canvas1Ctx.fillStyle = 'black'
canvas1Ctx.fillRect(300, 100, 100, 100)
const animateCanvas = () => {
x += 2;
if (x > 300) x = 10
canvas1Ctx.fillStyle = 'rgba(20,20,20,1)'
canvas1Ctx.fillRect(0, 0, canvas.width, canvas.height)
canvas1Ctx.beginPath()
canvas1Ctx.arc(x, 100, 20, 0, 2 * Math.PI)
canvas1Ctx.fillStyle = 'rgba(250,0,0,1)'
canvas1Ctx.fill()
requestAnimationFrame(animateCanvas)
}
animateCanvas()
}
const addOverlay = (canvas) => {
const canvasCtx = canvas2.getContext('2d')
function animateOverlay() {
canvasCtx.font = '48px serif'
canvasCtx.fillStyle = 'white'
canvasCtx.fillText(`X: ${x}`, 10, 50)
requestAnimationFrame(animateOverlay)
}
animateOverlay()
}
const initVideoCapture = () => {
var videoStream = canvas2.captureStream(30)
var mediaRecorder = new MediaRecorder(videoStream)
var chunks = []
mediaRecorder.ondataavailable = function(e) {
chunks.push(e.data)
}
mediaRecorder.onstop = function(e) {
var blob = new Blob(chunks, {
'type': 'video/mp4'
})
chunks = []
var videoURL = URL.createObjectURL(blob)
video.src = videoURL
}
mediaRecorder.ondataavailable = function(e) {
chunks.push(e.data)
}
mediaRecorder.start()
status.textContent = 'Recording...'
setTimeout(function() {
mediaRecorder.stop()
status.textContent = 'Complete'
}, 5000)
}
setupCanvas(canvas1)
setupCanvas(canvas2)
addOverlay(canvas2)
initVideoCapture()
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>
<video id="output" autoplay controls></video>
<p>Status: <span id="status">Loading</span></p>
Try this :
// show the distance a polyline has covered while animating it in mapbox gl js
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-74.5, 40],
zoom: 9,
})
var geojson = {
type: 'Feature',
properties: {},
geometry: {
type: 'LineString',
coordinates: [
[-74.5, 40],
[-74.45, 40.7],
[-74.36, 40.8],
[-74.36, 41.2],
],
},
}
map.on('load', function () {
map.addLayer({
id: 'route',
type: 'line',
source: {
type: 'geojson',
data: geojson,
},
layout: {
'line-join': 'round',
'line-cap': 'round',
},
paint: {
'line-color': '#888',
'line-width': 8,
},
})
var lineDistance = turf.lineDistance(geojson, 'kilometers')
var arc = []
var maxTravelTime = 0
for (var i = 0; i < lineDistance; i += lineDistance / 200) {
var segment = turf.along(geojson, i, 'kilometers')
arc.push(segment.geometry.coordinates)
}
map.addLayer({
id: 'point',
type: 'symbol',
source: {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
properties: {},
geometry: {
type: 'Point',
coordinates: arc[0],
},
},
],
},
},
layout: {
'icon-image': 'car',
'icon-rotate': ['get', 'bearing'],
'icon-rotation-alignment': 'map',
'icon-allow-overlap': true,
'icon-ignore-placement': true,
},
})
function animate() {
map.getSource('point').setData(geojson)
if (maxTravelTime < lineDistance) {
maxTravelTime += lineDistance / 200
} else {
maxTravelTime = 0
}
requestAnimationFrame(animate)
}
animate()
})

Chartjs animate x-axis displaying data incorrectly in mac device

I am working with chartjs, I am trying to animate chart from right to left or left to right on load.
var canvas = document.getElementById('chart_canvas');
var ctx = canvas.getContext('2d');
// Generate random data to plot
var DATA_POINT_NUM = 10;
var data = {
labels: [],
datasets: [
{
data: [],
},
]
}
for (var i=0; i<DATA_POINT_NUM; i++) {
data.datasets[0].data.push(Math.random()*10);
data.labels.push(String.fromCharCode(65+i));
}
var oldDraw = Chart.controllers.line.prototype.draw;
Chart.controllers.line.prototype.draw = function(animationFraction) {
var animationConfig = this.chart.options.animation;
if (animationConfig.xAxis === true) {
var ctx = this.chart.chart.ctx;
var hShift = (1-animationFraction)*ctx.canvas.width;
ctx.save();
ctx.setTransform(1, 0, 0, 1, hShift,0);
if (animationConfig.yAxis === true) {
oldDraw.call(this, animationFraction);
} else {
oldDraw.call(this, 1);
}
ctx.restore();
} else if (animationConfig.yAxis === true) {
oldDraw.call(this, animationFraction);
} else {
oldDraw.call(this, 1);
}
}
var lineChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
animation: {
duration: 5000,
xAxis: true,
yAxis: true,
}
}
});
Example 1
The above code works fine on windows, but I'm facing issue on mac devices.While animating from left to right the data displays incorrectly means that the data moves to upward from x axis.How to fix this issue?
I am attaching screenshot.
Screenshot
Please change setTransform to transform.
Try the following code
var canvas = document.getElementById('chart_canvas');
var ctx = canvas.getContext('2d');
// Generate random data to plot
var DATA_POINT_NUM = 10;
var data = {
labels: [],
datasets: [
{
data: [],
},
]
}
for (var i=0; i<DATA_POINT_NUM; i++) {
data.datasets[0].data.push(Math.random()*10);
data.labels.push(String.fromCharCode(65+i));
}
var oldDraw = Chart.controllers.line.prototype.draw;
Chart.controllers.line.prototype.draw = function(animationFraction) {
var animationConfig = this.chart.options.animation;
if (animationConfig.xAxis === true) {
var ctx = this.chart.chart.ctx;
var hShift = (1-animationFraction)*ctx.canvas.width;
ctx.save();
ctx.transform(1, 0, 0, 1, hShift,0);
if (animationConfig.yAxis === true) {
oldDraw.call(this, animationFraction);
} else {
oldDraw.call(this, 1);
}
ctx.restore();
} else if (animationConfig.yAxis === true) {
oldDraw.call(this, animationFraction);
} else {
oldDraw.call(this, 1);
}
}
var lineChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
animation: {
duration: 5000,
xAxis: true,
yAxis: true,
}
}
});

Pan and zoom in kendo boxplot chart

I am trying to use the pan and zoom functionality in kendo box plot chart, can this be achieved for box plot chart.
http://demos.telerik.com/kendo-ui/bar-charts/pan-and-zoom
You can apply the exact same methods to the boxplot.
DEMO
CODE:
// Minimum/maximum number of visible items
var MIN_SIZE = 6;
var MAX_SIZE = 18;
// Optional sort expression
// var SORT = { field: "val", dir: "asc" };
var SORT = {};
// Minimum distance in px to start dragging
var DRAG_THR = 50;
// State variables
var viewStart = 0;
var viewSize = MIN_SIZE;
var newStart;
// Drag handler
function onDrag(e) {
var chart = e.sender;
var ds = chart.dataSource;
var delta = Math.round(e.originalEvent.x.initialDelta / DRAG_THR);
if (delta != 0) {
newStart = Math.max(0, viewStart - delta);
newStart = Math.min(data.length - viewSize, newStart);
ds.query({
skip: newStart,
page: 0,
pageSize: viewSize,
sort: SORT
});
}
}
function onDragEnd() {
viewStart = newStart;
}
// Zoom handler
function onZoom(e) {
var chart = e.sender;
var ds = chart.dataSource;
viewSize = Math.min(Math.max(viewSize + e.delta, MIN_SIZE), MAX_SIZE);
ds.query({
skip: viewStart,
page: 0,
pageSize: viewSize,
sort: SORT
});
// Prevent document scrolling
e.originalEvent.preventDefault();
}
$("#chart").kendoChart({
dataSource: {
data: data,
pageSize: viewSize,
page: 0,
sort: { }
},
title: {
text: "Ozone Concentration (ppm)"
},
legend: {
visible: false
},
series: [{
type: "boxPlot",
lowerField: "lower",
q1Field: "q1",
medianField: "median",
q3Field: "q3",
upperField: "upper",
meanField: "mean",
outliersField: "outliers"
}],
categoryAxis: {
field: "year",
majorGridLines: {
visible: false
}
},
transitions: false,
drag: onDrag,
dragEnd: onDragEnd,
zoom: onZoom
});

A marker can only be added to a layer of type "group" error even though type "group" is defined

I am having trouble with an error that seems obvious but I've tried everything. I must be missing something. I'm running a rails app with Angularjs and angular-leaflet-directives. I am trying to add markers to a specific group. No matter what I do, I keep getting this error:
[AngularJS - Leaflet] A marker can only be added to a layer of type "group"
I know that this error comes up when the overlays type isn't group. The issue is that in my case, it is!
EDIT: here is a plunkr where I recreated the bug: http://plnkr.co/edit/DLCN5RYVr0BheYzTuqkQ?p=preview
Here is my code:
assets/javascript/angular/services/service.js
app.factory('Markers', ["$http", "$q", function($http, $q) {
var Markers = []
var events_markers = []
var stories_markers = []
var defaultIcon = L.icon({
iconUrl: 'assets/dot-grey.png',
iconSize: [15, 15],
iconAnchor: [15, 15],
popupAnchor: [-7, -20]
})
// Getting events + stories from rails API
var event_data = $http.get("/api/v1/events.json"),
story_data = $http.get("/api/v1/stories.json")
// Setting event markers and stories markers
$q.all([event_data, story_data]).then(function(results) {
var data_stories = results[1].data.stories
var data_events = results[0].data.event
for (i=0 ; i < data_stories.length; i++){
for (j=0; j < data_stories[i].locations.length; j++){
var lat = data_stories[i].locations[j].latitude
var lng = data_stories[i].locations[j].longitude
var title = data_stories[i].title
var layer = "stories"
Markers.push({layer: layer, lat:lat, lng:lng, message: title, icon: defaultIcon})
}
}
for (e=0 ; e < data_events.length; e++){
if (data_events[e].latitude != null){
var lat = data_events[e].latitude
var lng = data_events[e].longitude
var title = data_events[e].name
var layer = "events"
Markers.push({layer: layer, lat:lat, lng: lng, message: title, icon: defaultIcon})
}
}
return Markers
});
return {
markers: Markers
}
}]);
assets/javascript/angular/controllers/MapCtrl.js
app.controller("MapCtrl", ['$scope', "$timeout", "leafletData", "Markers", function($scope,
$timeout, leafletData, Markers ){
$scope.isVisible = true;
$scope.markers = Markers.markers;
var bounds = {
northEast:{
lat: 37.86862005954327,
lng: -122.12230682373048
},
southWest:{
lat: 37.68436373334184,
lng: -122.55901336669923
}
}
function setMap($scope, markers, bounds) {
angular.extend($scope, {
maxbounds: bounds,
defaults: {
scrollWheelZoom: false,
maxZoom: 14,
minZoom: 10
},
layers: {
baselayers: {
mapbox:{
name: 'Mapbox Litography',
url: 'http://api.tiles.mapbox.com/v4/{mapid}/{z}/{x}/{y}.png?access_token={apikey}',
type: 'xyz',
layerParams: {
apikey: 'pk.eyJ1IjoibGF1cmVuYmVuaWNob3UiLCJhIjoiQ1BlZGczRSJ9.EVMieITn7lHNi6Ato9wFwg',
mapid: 'laurenbenichou.jm96meb6'
}
}
}
},
overlays: {
stories: {
type: 'group', //Note here that the type is indeed 'group'
name: 'stories',
visible: true
},
events: {
type: 'group',
name: 'events',
visible: false
}
},
markers: markers
});
}
setMap($scope, $scope.markers, bounds)
angular.element(document).ready(function () {
function toggle(){$scope.isVisible = !$scope.isVisible;}
$timeout(toggle, 1000);
});
}])
assets/javascript/templates/map.html
<leaflet ng-hide="isVisible" defaults="defaults" markers="markers" layers="layers" height="100%" width="100%" maxbounds="maxbounds" ></leaflet>
assets/javascript/angular/app.js
var app = angular.module("litography", ['ngAnimate','ui.router','ngResource', 'templates', 'leaflet-directive', 'cn.offCanvas', 'ui.bootstrap', 'angular-flexslider'])
.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {
/**
* Routes and States
*/
$stateProvider
.state('home', {
url: "/",
views:{
"splash": {
templateUrl: "splash.html",
controller: "SplashCtrl"
},
"map":{
templateUrl: "map.html",
controller: "MapCtrl",
resolve:{
Markers: function(Markers){
return Markers
}
}
},
"menu":{
templateUrl: "menu.html",
controller: "MenuCtrl"
}
}
})
// default fall back route
$urlRouterProvider.otherwise('/');
// enable HTML5 Mode for SEO
$locationProvider.html5Mode(true);
}]);
It can happen if you forgot to add the file: leaflet.markercluster.js
Ok, from the reduced plunker it was easier to play around and find the bug.
You need to put overlays inside (i.e. as a property of) layers:
layers: {
baselayers: {
mapbox: {
name: 'mapbox',
url: 'http://api.tiles.mapbox.com/v4/{mapid}/{z}/{x}/{y}.png?access_token={apikey}',
type: 'xyz',
layerParams: {
apikey: 'pk.eyJ1IjoibGF1cmVuYmVuaWNob3UiLCJhIjoiQ1BlZGczRSJ9.EVMieITn7lHNi6Ato9wFwg',
mapid: 'laurenbenichou.jm96meb6',
name: "stories"
}
}
},
overlays: {
stories: {
type: 'group',
name: 'stories',
visible: true,
},
events: {
type: 'group',
name: 'events',
visible: false
}
}
}

Post back with Dojo Dropdown

I have a dojo dropdown and I want to add a post back even to it. This is because I want to load other controls based on the value selected from the drop down. How can I achieve something like this? This is ASP.NET MVC.
Here is what I have.
#model String
#{
var id = ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty);
var name = ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty);
}
<select title="Country" name="dropDownList" id="dropDownList" style="width: 140px">
<option value=""></option>
<option value="USA">USA</option>
<option value="UK">UK</option>
</select>
<script type="text/javascript">
dojo.addOnLoad(function () {
dojo.connect(dojo.byId('#dropDownList'), "onchange", function (evt) {
//var selectedVal = dojo.byId('#dropDownList').get('value');
alert("changed!");
location.href = '/Provisioning/Country';
//alert(selectedVal);
});
});
</script>
I am able to get the alert and also able to stop # the break point in controller. But how can I now pass my value selected???
Thanks,
Vivek
var _data = [
{ objectid: 10, district: "dist1", meterid: "meter10", premise: "premise1", blinkcount: 100 },
{ objectid: 11, district: "dist1", meterid: "meter11", premise: "premise100", blinkcount: 200 },
{ objectid: 12, district: "dist3", meterid: "meter160", premise: "premise1", blinkcount: 100 },
{ objectid: 13, district: "dist3", meterid: "meter12", premise: "premise101", blinkcount: 300 },
{ objectid: 14, district: "dist1", meterid: "meter180", premise: "premise1", blinkcount: 100 },
{ objectid: 15, district: "dist2", meterid: "meter13", premise: "premise102", blinkcount: 400 },
{ objectid: 16, district: "dist3", meterid: "meter1", premise: "premise1", blinkcount: 100 },
{ objectid: 17, district: "dist2", meterid: "meter14", premise: "premise103", blinkcount: 500 }];
let districtdata = [];
for (let i = 0; i < _data.length; i++) {
districtdata.push({ id: i, label: _data[i].district });
}
let meterdata = [];
for (let i = 0; i < _data.length; i++) {
meterdata.push({ id: i, label: _data[i].meterid });
}
let premisedata = [];
for (let i = 0; i < _data.length; i++) {
premisedata.push({ id: i, label: _data[i].premise });
}
let diststore = Observable(new Memory({
data: districtdata
}));
let distos = new ObjectStore({ objectStore: diststore });
let meterstore = Observable(new Memory({
data: meterdata
}));
let meteros = new ObjectStore({ objectStore: meterstore });
let premisestore = Observable(new Memory({
data: districtdata
}));
let premiseos = new ObjectStore({ objectStore: premisestore });
let district = new Select({
store: distos
}, "district");
district.startup();
var meter = new Select({
store: meteros
}, "meter");
meter.startup();
var premise = new Select({
store: premiseos
}, "premise");
premise.startup();
district.on("change", function () {
console.log("my value: ", this.get("value"));
meterdata = [];
for (let i = 0; i < _data.length; i++) {
if (_data[i].district === this.options[this.get("value")].label) {
meterdata.push({ id: i, label: _data[i].meterid });
}
}
meterstore = Observable(new Memory({
data: meterdata
}));
meteros = new ObjectStore({ objectStore: meterstore });
meter.setStore(meteros);
})
meter.on("change", function () {
console.log("my value: ", this.get("value"))
})
premise.on("change", function () {
console.log("my value: ", this.get("value"))
})

Resources