I am trying to display and refresh periodically some server data using dgrid and derivative of Request dstore. The data are paginated and needs to be updated periodically. As a first naive approach I tried to call Dgrid.refresh() with setInterval. However, that results in complete rebuilding of grid rows which visually creates flickering effect. Using Trackable to the store does not help. Can anyone advise me how to refresh rows in the dgrid which would only update changed rows?
Here is my code reproducing the issue:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DGrid flickering on slow updates</title>
<style>
#import "./dojo-release-1.11.1/dojo/resources/dojo.css";
#import "./dojo-release-1.11.1/dijit/themes/claro/claro.css";
#import "./META-INF/resources/webjars/dgrid/1.0.0/css/dgrid.css";
#import "./META-INF/resources/webjars/dgrid/1.0.0/css/skins/claro.css";
html, body {
padding: 10px;
width: 100%;
height: 100%;
}
</style>
<script>
var dojoConfig = {
async:true,
baseUrl: "./",
packages:[
{ name:"dojo", location:"dojo-release-1.11.1/dojo" },
{ name:"dijit", location:"dojo-release-1.11.1/dijit" },
{ name:"dgrid", location:"META-INF/resources/webjars/dgrid/1.0.0" },
{ name:"dstore", location:"META-INF/resources/webjars/dstore/1.1.1" }
]
};
</script>
<script src="dojo-release-1.11.1/dojo/dojo.js"></script>
<script>
require(["dojo/parser",
"dojo/dom",
"dojo/_base/declare",
"dstore/Store",
"dstore/Trackable",
"dstore/Cache",
"dstore/Memory",
"dstore/QueryResults",
"dojo/Deferred",
"dgrid/Grid",
"dgrid/Keyboard",
"dgrid/Selection",
"dgrid/extensions/Pagination",
"dojo/domReady!"],
function(parser, dom, declare, Store, Trackable, Cache, Memory, QueryResults, Deferred, Grid, Keyboard, Selection, Pagination)
{
parser.parse();
console.log("Parsed");
var makeSlowRequest =
function(kwArgs)
{
var responseDeferred = new Deferred();
var responsePromise = responseDeferred.promise;
// resolve promise in 2 seconds to simulate slow network connection
setTimeout(function ()
{
console.log("Generating response");
var data = {items: [], total: 100};
kwArgs = kwArgs || {start:0, end:100};
for(var i = kwArgs.start; i < kwArgs.end; i++)
{
data.items.push({id: "id-" + i,
name: "test-" + i,
value: Math.floor((Math.random() * 10) + kwArgs.start)
});
}
responseDeferred.resolve(data);
}, 2000);
return new QueryResults(responsePromise.then(function (data) { return data.items; }),
{ totalLength: responsePromise.then(function (data) { return data.total;}) });
};
var SlowStore = declare("SlowStore",
[Store, Trackable],
{ fetch: function (kwArgs) { return makeSlowRequest(kwArgs); },
fetchRange: function (kwArgs) { return makeSlowRequest(kwArgs); }
});
var store = new SlowStore();
var TestGrid = declare([Grid, Keyboard, Selection, Pagination]);
var grid = new TestGrid({
collection: store,
columns: {name: "Name", value: "Value"},
rowsPerPage: 10,
selectionMode: 'single',
cellNavigation: false,
className: 'dgrid-autoheight',
pageSizeOptions: [10, 20],
adjustLastColumn: true
}, dom.byId("grid"));
grid.startup();
// update grid every 5 seconds
var timer = setInterval(function(){console.log("Refreshing grid"); grid.refresh();}, 5000);
});
</script>
</head>
<body class="claro">
<div id="grid"></div>
</body>
</html>
I am guessing that instead of calling refresh I need get the request range from the dgrid (possibly using aspect on gotoPage) and call store.fetchRange(), iterate over the results, compare each item with previous results and invoke store.update or store.add or store.delete. I suppose that would give me what I want but before taking this approach I wondering if there is an easier way to refresh dgrid with updated data. Using Cache store does not work as it expects to fetch all the data from the server:
var store = Cache.create(new SlowStore(), {
cachingStore: new (Memory.createSubclass(Trackable))()
});
Related
app.component.html
This is my app.component file where i show my chart
<div style="display: block;">
<canvas baseChart width="400" height="400"
[datasets]="lineChartData"
[labels]="lineChartLabels"
[options]="lineChartOptions"
[colors]="lineChartColors"
[legend]="lineChartLegend"
[chartType]="lineChartType">
</canvas>
</div>
app.component.ts
My ts file where the logic impleneted i have issue there i am not know how to perform logic to show the data i have issue how to create method in it which will call in the app.component.html file
constructor(private chartService: ChartServiceService) { }
ngOnInit(): void {
this.getlinechart();
}
getlinechart(){
this.chartService.getLineChart().subscribe(res => {
this.linechart = res;
console.log(res);
let lincechartData = res.list[0].data;
let lincechartLabels = res.list[0].graphlabels;
public lineChartData:any = this.lincechartData;
**I,m facing issue here above to create method to store the
data and used in html compiler give the error this ,'
expected.ts(1005)
Cannot find name 'lineChartData'**
});
}
app.service.ts
This is service file which getting the data from the backend nodejs api
getLineChart(){
return this.httpClient.get<any>
('http://localhost:3000/api/chart/line')
.pipe(
map(result => result)
)
}
If i undestand correctly you are trying to read data from a database and put it on a chart. I did something similar, but i had a bit different approach:
HTML:
<canvas id="myChart" width="300" height="100"></canvas> <br/>
Chart config:
var config = {
type: 'line',
data: { datasets: [] }, // trend data goes here
options: {
scales: {
xAxis: { // x axis
type: 'time',
}
},
},
}
New chart:
function newChart() {
config.data.datasets = []; // reset data
populateTrend(config); // populate chart
if (window.hasOwnProperty("graph")) { // destroy previous chart
if (typeof window.graph.resetZoom !== "undefined") { // if you have a zoom plugin
window.graph.resetZoom();
}
window.graph.destroy();
}
let ctx = document.getElementById('myChart').getContext('2d'); // canvas
window.graph = new Chart(ctx, config); // make the chart
}
populate trend:
function populateTrend (config) {
// data sets and scales
let datasets = config.data.datasets, scales = config.options.scales;
let log = data; // this is where you read from your database
let dataset = { // add some data here
data: [],
label: log.description,
fill: false,
radius: 0,
unit: log.unit,
pointType: log.pointType,
yAxisID: log.unit, // y axis
};
// this is where the real data goes
// you should push the data in a loop
dataset.data.push({
"x": something.getTime(),
"y": null,
"ymin": null,
"ymax": null,
});
datasets.push(dataset); // add data set to config
}
To reproduce:
Run the Code Snippet (recommend Full Page mode)
Hold Ctrl or Shift while clicking to select multiple 'species' in the table column header
Note that while the key is held down, the table data is filtered according to selected 'species'
Release the key, observe changes in filtered table data
I think this is probably related to https://github.com/olifolkerd/tabulator/issues/975 and that I need to do something to override default tabulator keypress events.
JSFiddle: https://jsfiddle.net/jjech/3th28pv0/229/
const speciesTypes = [ 'Human', 'Android', 'Betazoid', 'Klingon', 'Ferengi', 'Tamarian' ];
function multiSelectHeaderFilter(cell) {
var values = speciesTypes;
const filterFunc = (rowData) => {
return values.includes(rowData['species']);
}
const getSelectedValues = (multiSelect) => {
var result = [];
var options = multiSelect && multiSelect.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
const onChange = () => {
var editor = document.getElementById('speciesSelector');
values = getSelectedValues(editor);
console.log("values: "+values);
cell.getColumn().getTable().removeFilter(filterFunc);
cell.getColumn().getTable().addFilter(filterFunc);
}
var select = document.createElement("select");
select.multiple = "multiple";
select.id = 'speciesSelector';
select.style = 'width: 100%';
speciesTypes.forEach(species => {
select.innerHTML += "<option id='"+species+"' value='"+species+"' selected='selected'>"+species+"</option>";
});
cell.getColumn().getTable().addFilter(filterFunc);
select.addEventListener('change',onChange);
return select;
}
var table = new Tabulator("#tabulator", {
layout:"fitColumns",
data:[ {name:'Geordi La Forge',species:'Human'}, {name:'Dathon', species:'Tamarian'}, {name:'Jean-Luc Picard', species:'Human'}, {name:'Worf, son of Mogh', species:'Klingon'}, {name:'Tasha Yarr', species:'Human'}, {name:'Data', species:'Android'}, {name:'Wesley Crusher', species:'Human'}, {name:'Jalad', species:'Tamarian'}, {name:'Lwaxana Troi', species:'Betazoid'}, {name:'Temba', species:'Tamarian'}, {name:'T\'Kuvma', species:'Klingon'}, {name:'Lore', species:'Android'}, {name:'Noonian Soongh', species:'Human'}, {name:'Darmok', species:'Tamarian'}, {name:'Reittan Grax', species:'Betazoid'}, {name:'Quark', species:'Ferengi'} ],
headerSort:true,
columns:[ {title:'Name',field:'name',sorter:'string'},{title:'Species',field:'species',sorter:'string',headerFilter:multiSelectHeaderFilter }, ],
});
//document.multiselect('#speciesSelector');
<html>
<head>
<link href="https://unpkg.com/tabulator-tables#4.5.3/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#4.5.3/dist/js/tabulator.min.js"></script>
<link href="https://cdn.jsdelivr.net/gh/mneofit/multiselect/styles/multiselect.css" rel="stylesheet">
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/mneofit/multiselect/multiselect.min.js"></script>
<script></script>
<style>
.tabulator .tabulator-header,
.tabulator .tabulator-header .tabulator-col
{
overflow: unset;
}
</style>
</head>
<body>
<div id="tabulator"></div>
</body>
</html>
Fixed by adding headerFilterLiveFilter:false to the column definition.
columns:[ {title:'Name',field:'name',sorter:'string'},{title:'Species',field:'species',sorter:'string',headerFilter:multiSelectHeaderFilter,headerFilterLiveFilter:false }, ],
https://jsfiddle.net/jjech/3th28pv0/237/
My NodeJS GET route:
router.get('/stores', function (req, res, next) {
errorMsg = req.flash('error')[0];
successMsg = req.flash('success')[0];
Product.find(function (err, products) {
// console.log(products)
res.render('admin/stores', {
layout: 'admin-map.hbs',
stores: products,
errorMsg: errorMsg,
GOOGLE_APIKEY: process.env.GOOGLE_APIKEY,
noErrors: 1
});
});
The route /stores returns json data which holds latitude and longitude and I want it in my script tag of map.html with loop, to render the pins on the map. Below, the script:
<!DOCTYPE html>
<html>
<head>
<script src = "https://maps.googleapis.com/maps/api/js"></script>
<script>
function loadMap() {
alert(this.stores);
var mapOptions = {
center:new google.maps.LatLng(17.433053, 78.412172),
zoom:5
}
var map = new google.maps.Map(document.getElementById("sample"),mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(17.433053, 78.412172),
map: map,
draggable:true,
icon:'/scripts/img/logo-footer.png'
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({ });
infowindow.open(map,marker);
}
</script>
<!-- ... -->
</head>
</html>
How can I do it?
It seems you need to follow two steps
1. Pass data from hbs to script
Using triple brackets syntax
<script>
let stores = {{{ stores }}}; // the triple brackets
console.log('Data : ', stores);
function loadMap() {
...
Check if data is being printed in console? If yes your data is available in the front-end script and you can
2. Loop through it
...
for (let i = 0; i < stores.length; i++) {
// the JS loop instead of hbs one, because we are on front-end
var marker = new google.maps.Marker({
position: new google.maps.LatLng(stores[i].lat, stores[i].lng), // whatever applies
map: map,
draggable:true,
icon:'/scripts/img/logo-footer.png'
});
}
And donot need to call setMap(), you have already set the map in map: map above
the answer is inside fronted script i can have an object declared globally and this double flower brackets works fine with them
<script>
function loadMap() {
alert(this.stores);
var mapOptions = {
center:new google.maps.LatLng(17.433053, 78.412172),
zoom:5
}
var map = new google.maps.Map(document.getElementById("sample"),mapOptions);
{{#each stores}}
var marker = new google.maps.Marker({
position: new google.maps.LatLng(17.433053, 78.412172),
map: map,
draggable:true,
icon:'/scripts/img/logo-footer.png'
});
{{/each}}
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({ });
infowindow.open(map,marker);
}
</script>
Has somebody already achieved to display a chart, not based on timeseries (like the chart from the dashboard), but on data passed to it?
I wonder if it is, perhaps, possible to use a template to do that? But I've no clue how to do it. If someone has a small example, it would be great.
I've found a solution, using some code sample from the library...
The link between msg.payload and data is still missing, but not far away
<style>
#chart svg {
width: 800px;
height: 600px;
}
</style>
<h3>test</h3>
<div id="chart">
<svg></svg>
</div>
<script src="https://raw.githubusercontent.com/novus/nvd3/master/build/nv.d3.js"></script>
<script>
(function(scope) {
console.log('Position 1');
console.dir(scope);
console.log(scope.msg);
scope.$watch('msg.payload', function(data) {
console.log('Position 2');
console.dir(data);
});
})(scope);
function data() {
var sin = [],
cos = [];
for (var i = 0; i < 100; i++) {
sin.push({x: i, y: Math.sin(i/10)});
cos.push({x: i, y: .5 * Math.cos(i/10)});
}
return [
{
values: sin,
key: 'normal',
color: '#ff7f0e'
},
{
values: cos,
key: 'defect',
color: '#2ca02c'
}
];
}
nv.addGraph(function() {
var chart = nv.models.lineChart()
.useInteractiveGuideline(true)
;
chart.xAxis
.axisLabel('frequence')
.tickFormat(d3.format(',r'))
;
chart.yAxis
.axisLabel('amplitude')
.tickFormat(d3.format('.02f'))
;
d3.select('#chart svg')
.datum(data())
.transition().duration(500)
.call(chart)
;
nv.utils.windowResize(chart.update);
return chart;
});
</script>
I am using EXT.NET and have a question. I have a trouble to load json data into grid panel. My code is below. When tree item is clicked, selectNode function fires properly, but the JSON result can't be loaded into Grid panel.
How can I load into the Grid panel? Currently, white blank page pops up.
#model System.Collections.IEnumerable
#{
Layout = null;
var X = Html.X();
}
<script type="text/javascript">
var selectNode = function (item, record, node, index, event) {
Ext.Ajax.request({
url: "/Popup/GetDepartmentUser",
method: "POST",
params: {
id: record.data.id
},
callback: function (options, success, response) {
if (Ext.decode(response.responseText).success == false) {
Ext.Msg.alert("Failed", response.responseText);
} else {
var grid = App.theGrid;
grid.show();
grid.getStore().loadData(Ext.decode(response.responseText));
//Ext.Msg.alert("Success", response.responseText);
}
},
failure: function (response, options) {
Ext.MessageBox.alert("Failed", response.responseText);
},
timeout: '10000'
});
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>Search User</title>
</head>
<body>
#(Html.X().ResourceManager())
#(X.Panel()
.Layout(LayoutType.Border)
.Width(780)
.Height(460)
.Items(
X.TreePanel()
.Title("Department")
.ID("theTree")
.Region(Region.West)
.Width(250)
.Height(460)
.Border(false)
.Split(true)
.UseArrows(true)
.Listeners(l => l.ItemClick.Fn = "selectNode")
.Store(
Html.X().TreeStore()
.Proxy(
Html.X().AjaxProxy().Url(Url.Action("GetDepartmentChildren"))
)
)
.Root(
Html.X().Node().NodeID("0").Text(ViewBag.OrganizationName)
),
Html.X().GridPanel()
.ID("theGrid")
.Title("User Information")
.Region(Region.Center)
.Width(530)
.Height(460)
.Border(false)
.Store(Html.X().Store()
.AutoLoad(false)
.Model(Html.X().Model()
.Fields(
new ModelField("FirstName", ModelFieldType.String),
new ModelField("LastName", ModelFieldType.String),
new ModelField("Email", ModelFieldType.String)
)
)
//.DataSource(Model)
.Reader(reader => reader.Add(Html.X().JsonReader().Root("data")))
)
.ColumnModel(
Html.X().Column()
.Text("First Name")
.DataIndex("FirstName")
.Flex(1),
Html.X().Column()
.Text("LastName")
.DataIndex("LastName")
.Width(70)
.Align(Alignment.Center),
Html.X().Column()
.Text("Email")
.DataIndex("Email")
.Width(140)
)
.View(Html.X().GridView().StripeRows(true).TrackOver(true))
)
)
</body>
</html>
Here is JSON result data
{
"success":true,
"total":2,
"data":"[
{
\"FirstName\":\"BlahBlah1\",
\"LastName\":\"Kwak\",
\"Email\":\"BlahBlah1#hotmail.com\"
},
{
\"FirstName\":\"BlahBlah2\",
\"LastName\":\"Kwak\",
\"Email\":\"BlahBlah1#hotmail.com\"
}
]"
}
I found that loadData method reads only Model record data.
So, I fixed it by using loadRawData method instead loadData.