Fuelux - how to use repeater - javascript

I am trying to use Fuelux repeater for one of my projects but I cant figure out how to populate data using javascript. The examples they have provided use couple of other plugins(Require.js and underscore.js) and I am not familiar with those. Can someone please help me to do this without any other plugins. I removed all require methods in the code but that didnt work either. Please look at this fiddle for what I have so far.
/*!
* JavaScript for Fuel UX's docs - Repeater Examples
* Copyright 2011-2014 ExactTarget, Inc.
* Licensed under the Creative Commons Attribution 3.0 Unported License. For
* details, see http://creativecommons.org/licenses/by/3.0/.
*/
define function(require){
// var $ = require('jquery');
// var _ = require('underscore');
var colors = {
bug: '#A8B820',
dark: '#705848',
dragon: '#7038F8',
electric: '#F8D030',
fairy: '#EE99AC',
fighting: '#C03028',
fire: '#F08030',
flying: '#A890F0',
ghost: '#705898',
grass: '#78C850',
ground: '#E0C068',
ice: '#98D8D8',
normal: '#A8A878',
poison: '#A040A0',
psychic: '#F85888',
rock: '#B8A038',
steel: '#B8B8D0',
water: '#6890F0'
};
var columns = [
{
label: 'Name',
property: 'name',
sortable: true
},
{
label: 'Id',
property: 'id',
sortable: true
},
{
label: 'Type',
property: 'type',
sortable: true
},
{
label: 'Height (in)',
property: 'height',
sortable: true
},
{
label: 'Weight (lbs)',
property: 'weight',
sortable: true
},
{
label: 'Abilities',
property: 'abilities',
sortable: true
},
{
label: 'Weakness',
property: 'weakness',
sortable: true
}
];
var delays = ['300', '600', '900', '1200'];
var pokemon = [{
"abilities": "Overgrow",
"weight": "15.2",
"weakness": "fire, flying, ice, psychic",
"height": "28.0",
"id": "001",
"name": "Bulbasaur",
"ThumbnailAltText": "Bulbasaur",
"ThumbnailImage": "http://assets2.pokemon.com/assets/cms2/img/pokedex/detail/001.png",
"type": "grass, poison"
},
{
"abilities": "Overgrow",
"weight": "28.7",
"weakness": "fire, flying, ice, psychic",
"height": "39.0",
"id": "002",
"name": "Ivysaur",
"ThumbnailAltText": "Ivysaur",
"ThumbnailImage": "http://assets3.pokemon.com/assets/cms2/img/pokedex/detail/002.png",
"type": "grass, poison"
},
{
"abilities": "Overgrow, Thick Fat",
"weight": "342.8",
"weakness": "fire, psychic, flying, ice",
"height": "94.0",
"id": "003",
"name": "Venusaur",
"ThumbnailAltText": "Venusaur",
"ThumbnailImage": "http://assets4.pokemon.com/assets/cms2/img/pokedex/detail/003.png",
"type": "grass, poison"
}];
var dataSource, filtering;
// require('bootstrap');
// require('fuelux');
dataSource = function(options, callback){
var items = filtering(options);
var resp = {
count: items.length,
items: [],
page: options.pageIndex,
pages: Math.ceil(items.length/(options.pageSize || 50))
};
var i, items, l;
i = options.pageIndex * (options.pageSize || 50);
l = i + (options.pageSize || 50);
l = (l <= resp.count) ? l : resp.count;
resp.start = i + 1;
resp.end = l;
if(options.view==='list' || options.view==='thumbnail'){
if(options.view==='list'){
resp.columns = columns;
for(i; i<l; i++){
resp.items.push(items[i]);
}
}else{
for(i; i<l; i++){
resp.items.push({
color: colors[items[i].type.split(', ')[0]],
name: items[i].name,
src: items[i].ThumbnailImage
});
}
}
setTimeout(function(){
callback(resp);
}, delays[Math.floor(Math.random() * 4)]);
}
};
filtering = function(options){
var items = $.extend([], pokemon);
var search;
if(options.filter.value!=='all'){
items = _.filter(items, function(item){
return (item.type.search(options.filter.value)>=0);
});
}
if(options.search){
search = options.search.toLowerCase();
items = _.filter(items, function(item){
return (
(item.name.toLowerCase().search(options.search)>=0) ||
(item.id.toLowerCase().search(options.search)>=0) ||
(item.type.toLowerCase().search(options.search)>=0) ||
(item.height.toLowerCase().search(options.search)>=0) ||
(item.weight.toLowerCase().search(options.search)>=0) ||
(item.abilities.toLowerCase().search(options.search)>=0) ||
(item.weakness.toLowerCase().search(options.search)>=0)
);
});
}
if(options.sortProperty){
items = _.sortBy(items, function(item){
if(options.sortProperty==='id' || options.sortProperty==='height' || options.sortProperty==='weight'){
return parseFloat(item[options.sortProperty]);
}else{
return item[options.sortProperty];
}
});
if(options.sortDirection==='desc'){
items.reverse();
}
}
return items;
};
// REPEATER
$('#repeaterIllustration').repeater({
dataSource: dataSource
});
$('#myRepeater').repeater({
dataSource: dataSource
});
$('#myRepeaterList').repeater({
dataSource: dataSource
});
$('#myRepeaterThumbnail').repeater({
dataSource: dataSource,
thumbnail_template: '<div class="thumbnail repeater-thumbnail" style="background: {{color}};"><img height="75" src="{{src}}" width="65"><span>{{name}}</span></div>'
});
}

You seem to be doing everything right.. Only thing you had to do was load jQuery on onLoad and comment out define function(require) statement..
JSFiddle

Related

target.status value is not defined

var getOptArray = function (opt) {
var len = opt.length;
var res = [];
for (var i = 0; i < len; i++) {
res.push({text: (opt[i].text), value: opt[i].value, icon: opt[i].icon, color: opt[i].color});
}
return res;
}
var BLOG_CATEGORY_STATUS = {
prop: {text: "status", defval: false, class: "", size: "text-sm", margin: "m-r-xs", editable: [1, 2], tooltip: true},
publish: {text: "publishing", value: 1, icon: "fa fa-play", color: "green", question: "Publish"},
pause: {text: "paused", value: 2, icon: "fa fa-pause", color: "warning", question: "Pause"},
deleted: {text: "deleted", value: 3, icon: "fa fa-trash", color: "danger", question: "Delete"},
optArr: function () {
return getOptArray([this.publish, this.pause, this.deleted]);
},
/**
* opt example -> {status: foo, categoryId: fooValue, callback: fooFunction}
* #param {type} opt
*/
buildButton: function (opt) {
opt = opt || {};
var optArray = this.optArr();
var targetStatus = optArray[(opt.status) - 1];
console.log(targetStatus);
console.log(targetStatus.color); //prints "warning"
console.log(targetStatus.question); //prints "undefined"
var but = {};
return but;
}
};
$(function () {
BLOG_CATEGORY_STATUS.buildButton({categoryId: 1
, status: 2
, callback: function () {
console.log("test");
}})
});
I edit code to add as question in jsfiddle. it is ready to run in jsfiddle
in buildButton function, targetStatus.color is warning, for the same object, targetStatus.question is undefined. Can't see what i am missing.
You're probably missing the question data in the returned value from getOptArray:
res.push({
text: opt[i].text,
value: opt[i].value,
icon: opt[i].icon,
color: opt[i].color,
question: opt[i].question // <- here
});
Which, while you're at it, you should probably just rewrite this line as:
res.push(opt[i]);

How to export the percentage value in amchart V3 export functionality

I'm drawing a pie chart using AmCharts V3 and am using the export plugin to export the data as a file. I'm displaying a percentage contibution of the sale in different countries and would like to also display this percentage when I export my data to a CSV or XLSX file, but I'm not able to do so.
Here is my code
var chart = AmCharts.makeChart("chartdivtaxes", {
type: "pie",
startDuration: 0,
theme: "light",
addClassNames: true,
labelText: "[[percents]]",
innerRadius: "30%",
labelFunction: function(value, valueText, valueAxis) {
valueText = parseFloat(valueText);
var percentageText = valueText
.toFixed(1)
.replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
return percentageText + "%";
},
defs: {
filter: [
{
id: "shadow",
width: "200%",
height: "200%",
feOffset: {
result: "offOut",
in: "SourceAlpha",
dx: 0,
dy: 0
},
feGaussianBlur: {
result: "blurOut",
in: "offOut",
stdDeviation: 5
},
feBlend: {
in: "SourceGraphic",
in2: "blurOut",
mode: "normal"
}
}
]
},
dataProvider: [
{
countryName: "India",
country: "sale in india:",
litres: "800.00"
},
{
countryName: "africa",
country: "sale in africa:",
litres: "800.00"
},
{
countryName: "UK",
country: "sale in UK:",
litres: "800.00"
},
{
countryName: "US",
country: "sale in US:",
litres: "800.00"
}
],
valueField: "litres",
titleField: "country",
balloon: {
fixedPosition: false,
color: "#ffffff",
fillAlpha: 0.9,
fillColor: "#00000"
},
export: {
enabled: true,
divId: "exportLevy",
columnNames: {
litres: "TotalSale",
countryName: "Name"
},
menu: [
{
class: "export-main",
label: "Export",
menu: [
{
format: "XLSX"
},
{
format: "CSV"
}
]
}
],
exportFields: ["countryName", "litres", "percents"]
}
});
There are two ways you can go about this - both of which involve using the processData callback offered by the export plugin.
1) Use processData to add a percent property in your data and manually trigger a download with toCSV or toXLSX. Note that you will need to throw an exception to prevent the plugin from triggering the download multiple times:
var chart = AmCharts.makeChart("...", {
// ...
export: {
// ...
processData: function(data, cfg) {
//only for CSV and XLSX export. Wrap in an ignore call to prevent infinite loop
if ((cfg.format === "CSV" || cfg.format === "XLSX") && !cfg.ignoreThatRequest) {
var sum = data.reduce(function(accumulator, currentDataValue) {
return accumulator + parseFloat(currentDataValue.TotalSale);
}, 0);
data.forEach(function(currentDataValue) {
currentDataValue.percents =
(parseFloat(currentDataValue.TotalSale) / sum * 100).toFixed(1) + "%";
});
//will map to this.toCSV or this.toXLSX
this["to" + cfg.format]({
data: JSON.parse(JSON.stringify(data)),
ignoreThatRequest: true, //set ignore flag as processData will execute again when this is called
exportFields: ["Name", "TotalSale", "percents"]
},
function(output) {
this.download(output, cfg.mimeType, cfg.fileName + "." + cfg.extension);
}
);
throw "Invoked – Use custom handler (stop multiple download)"; //throw an exception to stop the multi-download attempt
}
return data;
}
}
});
Demo of method #1
2) Alternatively, add a dummy percents property in your dataProvider with its value set to null and use processData to fill it in before exporting the chart. This is simpler and doesn't require an exception workaround to prevent multiple downloads:
var chart = AmCharts.makeChart("...", {
// ...
export: {
// ...
processData: function(data, cfg) {
var sum = data.reduce(function(accumulator, currentDataValue) {
return accumulator + parseFloat(currentDataValue.TotalSale);
}, 0);
data.forEach(function(currentDataValue) {
currentDataValue.percents =
(parseFloat(currentDataValue.TotalSale) / sum * 100).toFixed(1) + "%";
});
return data;
}
}
});
Demo of method #2

ng-google-chart custom color for each column in column chart

I'm using the ng-google-charts module to build google charts for my angular application, what I'm trying to do is draw a column chart.
The code works the chart seems to be drawn correctly but I can't figure out how to add a colour in the rows I'm generating so that each column is coloured differently.
Here is my code, looking at google charts documentation it seems that I should be able to assign a hex code for each column but none of the examples I've seen use angular and none of them build their rows as literal objects like I need to do.
var collsArray = [];
var rowsArray = [];
for (var i = 0; i < vm.projects.length ; i++) {
//this is where I build each data row and where I think I need to add the color
rowsArray.push({
"c": [
{
"v": vm.projects[i].name
},
{
"v": vm.projects[i].developers,
"f": vm.projects[i].developers + ' developers working on ' + vm.projects[i].name
}]
});
}
collsArray = [{id: 'project', label: 'Project', type: 'string'},
{id: 'developers', label: 'Developers working', type: 'number'}];
vm.chartProjects = {
"type": "ColumnChart",
"displayed": false,
"data": {
"cols": collsArray,
"rows": rowsArray
},
"options": {
"isStacked": "true",
"fill": 0,
"width": '100%',
"height": '100%',
"displayExactValues": true,
"chartArea": {
"left": "1%",
"top": "1%",
"height": "98%",
"width": "98%"
}
},
"formatters": {},
"view": {}
};
Adding a Style Column Role is the easiest way to color an individual bar.
You could try something like this...
var colorPallette = [
'#7B241C', '#CB4335', '#FF9900', 'Gold', '#28B463',
'#196F3D', '#0D47A1', '#29B6F6', 'Indigo', 'Violet'
];
var collsArray = [];
var rowsArray = [];
collsArray = [
{id: 'project', label: 'Project', type: 'string'},
{id: 'developers', label: 'Developers working', type: 'number'},
{role: 'style', type: 'string'} // style column
];
var colorIndex = -1;
for (var i = 0; i < vm.projects.length ; i++) {
// manage color pallette
colorIndex++;
if (colorIndex === colorPallette.length) {
colorIndex = 0;
}
rowsArray.push({
"c": [
{
"v": vm.projects[i].name
},
{
"v": vm.projects[i].developers,
"f": vm.projects[i].developers + ' developers working on ' + vm.projects[i].name
},
{
"v": colorPallette[colorIndex] // style column
}
]
});
}
This answer shows the various color definitions you could use.
FYI: this option does not work with Material charts...

ExtJS 4.2 export grid data to downloadable CSV file

I want to create a download button in my EXT JS panel which when click download/exports EXTJS grid into downloadable CSV file.
PS: I think we can use store data or the JSON from which i am filling data in grid store to populate data into CSV file
I have tried Ext.ux.CSVExporter but i wasn't able to use it successfully.
My current code is :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title id='title'>HTML Page setup Tutorial</title>
<link rel="stylesheet" type="text/css" href="ext-all.css" />
<script type="text/javascript" src="ext-all.js"></script>
<script type="text/javascript" src="FileSaver.js"></script>
<script type="text/javascript" src="Formatter.js"></script>
<script type="text/javascript" src="CSVFormatter/CSVFormatter.js"></script>
<script type="text/javascript" src="ExcelFormatter/Cell.js"></script>
<script type="text/javascript" src="ExcelFormatter/Style.js"></script>
<script type="text/javascript" src="ExcelFormatter/Workbook.js"></script>
<script type="text/javascript" src="ExcelFormatter/Worksheet.js"></script>
<script type="text/javascript" src="ExcelFormatter/ExcelFormatter.js"></script>
<script type="text/javascript" src="Exporter.js"></script>
<script type="text/javascript" src="ExporterButton.js"></script>
<script type="text/javascript">
Ext.define('Ext.ux.ProgressBarPager', {
requires: ['Ext.ProgressBar'],
/**
* #cfg {Number} width
* <p>The default progress bar width. Default is 225.</p>
*/
width : 225,
/**
* #cfg {String} defaultText
* <p>The text to display while the store is loading. Default is 'Loading...'</p>
*/
defaultText : 'Loading...',
/**
* #cfg {Object} defaultAnimCfg
* <p>A {#link Ext.fx.Anim Ext.fx.Anim} configuration object.</p>
*/
defaultAnimCfg : {
duration: 1000,
easing: 'bounceOut'
},
/**
* Creates new ProgressBarPager.
* #param {Object} config Configuration options
*/
constructor : function(config) {
if (config) {
Ext.apply(this, config);
}
},
//public
init : function (parent) {
var displayItem;
if (parent.displayInfo) {
this.parent = parent;
displayItem = parent.child("#displayItem");
if (displayItem) {
parent.remove(displayItem, true);
}
this.progressBar = Ext.create('Ext.ProgressBar', {
text : this.defaultText,
width : this.width,
animate : this.defaultAnimCfg,
style: {
cursor: 'pointer'
},
listeners: {
el: {
scope: this,
click: this.handleProgressBarClick
}
}
});
parent.displayItem = this.progressBar;
parent.add(parent.displayItem);
Ext.apply(parent, this.parentOverrides);
}
},
// private
// This method handles the click for the progress bar
handleProgressBarClick : function(e){
var parent = this.parent,
displayItem = parent.displayItem,
box = this.progressBar.getBox(),
xy = e.getXY(),
position = xy[0]- box.x,
pages = Math.ceil(parent.store.getTotalCount() / parent.pageSize),
newPage = Math.max(Math.ceil(position / (displayItem.width / pages)), 1);
parent.store.loadPage(newPage);
},
// private, overriddes
parentOverrides : {
// private
// This method updates the information via the progress bar.
updateInfo : function(){
if(this.displayItem){
var count = this.store.getCount(),
pageData = this.getPageData(),
message = count === 0 ?
this.emptyMsg :
Ext.String.format(
this.displayMsg,
pageData.fromRecord, pageData.toRecord, this.store.getTotalCount()
),
percentage = pageData.pageCount > 0 ? (pageData.currentPage / pageData.pageCount) : 0;
this.displayItem.updateProgress(percentage, message, this.animate || this.defaultAnimConfig);
}
}
}
});
Ext.onReady(function() {
var field = [];
var columnList = [];
var counter = {
"levels":
[{
"name": "class",
"samples": [{
"name": "1660SH_3",
"features": [{
"count": 8,
"name": "Bacteroidia"
}, {
"count": 9,
"name": "Bacteroidiaa"
},
{
"count": 10,
"name": "Bacteroidiab"
},
{
"count": 11,
"name": "Bacteroidiac"
}]
}, {
"name": "1660SH_4",
"features": [{
"count": 5,
"name": "Bacteroidia"
}, {
"count": 6,
"name": "Bacteroidiaa"
},
{
"count": 7,
"name": "Bacteroidiab"
},
{
"count": 8,
"name": "Bacteroidiac"
}]
}]
}, ]
};
columnList.push({
header: "Sample v/s Feature",
dataIndex: "Sample v/s Feature",
width: 0.1 * Ext.getBody().getViewSize().width,
columnLines: true,
locked: true
});
field.push("Sample v/s Feature");
for (var p = 0; p < Object.keys(counter.levels[0].samples).length; p++) {
columnList.push({
header: counter.levels[0].samples[p].name,
dataIndex: counter.levels[0].samples[p].name,
flex: 1,
columnLines: true
});
field.push(counter.levels[0].samples[p].name);
}
if (counter.levels[0].name == 'class') {
var mydata=[];
for (var p = 0; p < Object.keys(counter.levels[0].samples[0].features).length; p++)
{
var s = [];
s["Sample v/s Feature"] = '<b>' + counter.levels[0].samples[0].features[p].name + '</b>';
for (var j = 0; j < Object.keys(counter.levels[0].samples).length; j++)
{
s[counter.levels[0].samples[j].name] = counter.levels[0].samples[j].features[p].count;
}
mydata.push(s);
}
var store = Ext.create('Ext.data.ArrayStore', {
autoLoad: false,
pageSize : 2,
fields: field,
data: {
count:mydata.length,
data:mydata
},
proxy:{
type:"memory",
enablePaging: true,
data:mydata,
reader: {
type: 'json',
root: 'data',
}
}
});
store.load({
params: {
// specify params for the first page load if using paging
start: 0,
limit: 2,
}
});
var classTable = Ext.create('Ext.grid.Panel', {
style: 'border: solid Blue 1px',
id: 'family',
renderTo: Ext.getBody(),
store: store,
requires: [
'Ext.ux.exporter.Exporter'
],
columns: columnList,
columnLines: true,
width: Ext.getBody().getViewSize().width,
height: Ext.getBody().getViewSize().height,
bbar: {
xtype: 'pagingtoolbar',
pageSize: 2,
store: store,
displayInfo: true,
plugins: new Ext.ux.ProgressBarPager()
},
dockedItems:[
{
xtype: 'toolbar',
dock: 'top',
items: [
{
xtype: 'exporterbutton',
text: 'export data'
}
]
}
]
});
}
});
</script>
</head>
<body>
</body>
</html>
repository link use this project
here is example how to use it fiddle link
first of all copy repository files to you ext library's ux folder located in ext/src/ux under exporter folder. full path will be ext/src/ux/exporter/[repository_files]
and modify your grid
var classTable = Ext.create('Ext.grid.Panel', {
style: 'border: solid Blue 1px',
id: 'family',
renderTo: Ext.getBody(),
store: store,
requires: [
'Ext.ux.exporter.Exporter'
],
columns: columnList,
columnLines: true,
width: Ext.getBody().getViewSize().width,
height: Ext.getBody().getViewSize().height,
bbar: {
xtype: 'pagingtoolbar',
pageSize: 2,
store: store,
displayInfo: true,
plugins: new Ext.ux.ProgressBarPager()
},
dockedItems:[
{
xtype: 'toolbar',
dock: 'top',
items: [
{
xtype: 'exporterbutton',
text: 'exrpot data'
}
]
}
]
});

How to improve performance of Highcharts and avoid error 15 inspite of sorted data?

I am trying to create a gantt chart representation in highcharts with navigator. I get a JSON response from server (below is a typical response strucutre). In order to create a gantt chart representation I am creating a line between 2 points. Each point has a start_date and end_date and inorder to create this representation I am plotting a line between start_date and end_date of each point (which I have accomplished).
Response Structure from server
{
"took": 312,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 4115,
"max_score": 1,
"hits": [
]
},
"aggregations": {
"top-tags": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "Process1",
"doc_count": 6,
"process": {
"value": {
"1449878649000": {
"start_date": 1449878649000,
"process_initiator": "lol#surg.com",
"end_date": 1449878734000,
"total_seconds": 85
},
"1449879753000": {
"start_date": 1449879753000,
"process_initiator": "lol#surg.com",
"end_date": 1449879850000,
"total_seconds": 97
},
"1449881550000": {
"start_date": 1449881550000,
"process_initiator": "lol#surg.com",
"end_date": 1449881631000,
"total_seconds": 81
}
}
}
},
{
"key": "Process2",
"doc_count": 1,
"process": {
"value": {
"1449971262000": {
"start_date": 1449971262000,
"process_initiator": "lol#surg.com",
"end_date": 1449971266000,
"total_seconds": 4
}
}
}
}
]
}
}
}
Code also sharing a plunker demo
var app = angular.module('app', []);
app.directive('operationalhighstackstock', function() {
return {
restrict: 'E',
scope: true,
link: function postLink(scope, element, attrs) {
scope.$watch('operationHighChartsData', function(values) {
new Highcharts.StockChart(values);
});
}
};
});
//2014-11-30T18:15:25.000-08:00
app.controller('MainCtrl', ['$scope', function($scope) {
$scope.excludeValue = {
data: 0
};
$scope.isExcludeNeeded = true;
var opExcludeMinutes = 1,
AGENT_NAMES = "agent_names",
colorCodes = ["#8CC051", "#967BDC", "#5D9CEC", "#FB6E52", "#EC87BF", "#46CEAD", "#FFCE55", "#193441", "#193441", "#BEEB9F", "#E3DB9A", "#917A56"];
var setSummaryDisplay = function(e) {
if (e.min === null || e.max === null)
$scope.hideRangeSlider = true;
else
$scope.hideRangeSlider = false;
$scope.minimumSelectedValue = e.min;
$scope.maximumSelectedValue = e.max;
}
var getHichartsData = function(result) {
var tasksArr = [],
seriesArr = [],
userArr = [],
processArr = [];
var agentSeries = [],
agentData = {},
processSeries = [],
taskData = {},
idx = 0,
opProcessBucket = esResponse.aggregations["top-tags"].buckets,
seriesData = {};
var opBucketLength = opProcessBucket.length;
for (var opProcessBucketIndex = 0; opProcessBucketIndex < opBucketLength; ++opProcessBucketIndex) {
//opProcessBucket.forEach(function(processEntry) {
//if (opProcessBucket[opProcessBucketIndex]["key"] == $scope.gpDropDownTitle) {
var intervalBucket = opProcessBucket[opProcessBucketIndex]["process"]["value"], //opProcessBucket[opProcessBucketIndex]["top_tag_hits"]["hits"]["hits"],
intervalArr = [],
tasksIntervalArr = [],
opTaskidObj = {},
opTaskidIntervalObj = {},
process_name = null,
sortElementArr = [];
for (var key in intervalBucket) {
//intervalBucket.forEach(function(intervalEntry, intervalIndex) {
var intervalObj = {},
intervalObj2ndpoint = {},
processIntervalObj = {},
tintervalArr = [],
intervalIndex = 0,
start_temp = parseInt(key),
end_temp = intervalBucket[key].end_date; //start_temp = intervalBucket[key].start_date, end_temp = intervalBucket[key].end_date;
//added here since response contains null value and data load will take almost 1 date, verified with Bhavesh
$scope.currentDateTime = new Date().getTime();
if (end_temp == null)
end_temp = $scope.currentDateTime;
var st = new Date(moment(start_temp).valueOf()).getTime();
var et = new Date(moment(end_temp).valueOf()).getTime();
var duration = moment.duration(moment(et).diff(moment(st)));
var minutes = duration.asMinutes();
if (minutes > $scope.excludeValue.data && $scope.isExcludeNeeded) {
if (intervalIndex == 0 || process_name == null) {
process_name = opProcessBucket[opProcessBucketIndex]["key"];
processArr.push(opProcessBucket[opProcessBucketIndex]["key"]);
}
userArr.push(intervalBucket[key].process_initiator);
processIntervalObj["task_id"] = opProcessBucket[opProcessBucketIndex]["key"];
processIntervalObj["from"] = st;
var lFromtime = moment.utc(st).toDate();
lFromtime = moment(lFromtime).format('MM/DD/YY HH:mm');
var lTotime = moment.utc(et).toDate();
lTotime = moment(lTotime).format('MM/DD/YY HH:mm');
processIntervalObj["to"] = et;
processIntervalObj["color"] = "#FFCC4E";
processIntervalObj["fromDateString"] = lFromtime;
processIntervalObj["toDateString"] = lTotime;
processIntervalObj["process_initiator"] = intervalBucket[key].process_initiator == null ? 'Unknown' : intervalBucket[key].process_initiator;
processIntervalObj["total_seconds"] = intervalBucket[key].total_seconds;
//sortElementArr.push(intervalEntry["sort"][0]);
tasksIntervalArr.push(processIntervalObj);
}
}
opTaskidObj["name"] = process_name;
opTaskidIntervalObj["name"] = process_name;
opTaskidObj["data"] = [];
opTaskidIntervalObj["intervals"] = tasksIntervalArr;
opTaskidIntervalObj["intervals"] = tasksIntervalArr;
idx++;
if (tasksIntervalArr.length > 0) {
processSeries.push(opTaskidIntervalObj);
agentSeries.push(opTaskidObj);
}
//}
}
seriesData["title"] = "Test"; //item["key"];
var series = [];
(processSeries.reverse()).forEach(function(task, i) {
var item = {
name: task.name,
data: [],
turboThreshold: 1100000
};
(task.intervals).forEach(function(interval, j) {
item.data.push({
task_id: interval.task_id,
x: interval.from,
y: i,
from: interval.from,
to: interval.to,
color: interval.color,
fromDateString: interval.fromDateString,
toDateString: interval.toDateString,
total_seconds: interval.total_seconds,
process_initiator: interval.process_initiator
}, {
task_id: interval.task_id,
x: interval.to,
y: i,
from: interval.from,
to: interval.to,
color: interval.color,
fromDateString: interval.fromDateString,
toDateString: interval.toDateString,
total_seconds: interval.total_seconds,
process_initiator: interval.process_initiator
});
// add a null value between intervals
if (task.intervals[j + 1]) {
item.data.push([(interval.to + task.intervals[j + 1].from) / 2, null]);
}
});
series.push(item);
})
seriesData["data"] = series;
seriesData["tasks"] = processSeries;
seriesArr.push(seriesData);
return seriesArr;
}
$scope.agentSeriesData = getHichartsData(esResponse);
var tasks = $scope.agentSeriesData[0].tasks;
var seriesData = $scope.agentSeriesData[0].data;
var xAxisStepping = 1 * 3600 * 1000;
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'container',
height: 600,
events: {
load: function(e) {
var max = this.xAxis[0].max;
var range = (24 * 3600 * 1000) * 7; // one day * 7
if ($scope.isInit || $scope.filterReseted) {
$scope.filterReseted = false;
this.xAxis[0].setExtremes(max - range, max);
}
setSummaryDisplay.call(this.xAxis[0], {
trigger: "navigator",
min: this.xAxis[0].min,
max: this.xAxis[0].max
});
}
}
},
title: {},
credits: {
enabled: false
},
xAxis: {
type: 'datetime',
gridLineWidth: 1,
tickInterval: xAxisStepping,
//ordinal:false,
dateTimeLabelFormats: {
month: '%b %e, %Y'
},
events: {
afterSetExtremes: setSummaryDisplay
},
minRange: 1000
},
yAxis: {
tickInterval: 1,
gridLineWidth: 1,
labels: {
enabled: false,
formatter: function() {
if (tasks[this.value]) {
return tasks[this.value].name;
}
}
},
startOnTick: false,
endOnTick: false,
title: {
text: 'Process'
}
},
animation: false,
rangeSelector: {
enabled: false
},
navigator: {
enabled: true
},
legend: {
enabled: false
},
tooltip: {
shared: false,
formatter: function() {
var str = '';
str += 'Process: ' + this.series.name + '<br>';
str += 'From: ' + Highcharts.dateFormat('%m/%d/%y %H:%M:%S', this.point.from) + '<br>';
str += 'To: ' + Highcharts.dateFormat('%m/%d/%y %H:%M:%S', this.point.to) + '<br>';
return str;
}
},
plotOptions: {
line: {
lineWidth: 10,
marker: {
enabled: false
},
dataLabels: {
enabled: false,
borderRadius: 5,
borderWidth: 1,
y: -6,
formatter: function() {
return this.series.name;
}
},
states: {
hover: {
lineWidth: 10
}
}
},
series: {
cursor: 'pointer',
animation: false,
point: {
events: {
click: function() {
$scope.selectedGuide = this.series.name;
//$scope.showTableView();
}
}
},
turboThreshold: 100000000,
dataGrouping: {
enabled: false
}
}
},
scrollbar: {
enabled: false
},
series: seriesData
});
$scope.operationHighChartsData = chart;
}]);
I have sorted data (ascending order) but I am still getting Highcharts error #15: www.highcharts.com/errors/15 errors in thousands (mostly 80k +), which is hanging the browser.
What could be the issue and how can I get rid of it and increase performance? Sharing a plunker which has code and relatively small number of errors.
Note: I am using Highstock JS v2.1.5
There are two problems with this code:
First thing you need to sort the series in ascending order of X. I did not want to debug your code on how do you construct your data so I added a simple loop in the end to sort everything.
for (var i in seriesData) {
seriesData[i].data.sort(function(a, b) {
if (a.x > b.x) {
return 1;
}
if (b.x > a.x) {
return -1;
}
return 0;
});
}
The other problem is that the data array contains in correct data because of this line
if (task.intervals[j + 1]) {
item.data.push([(interval.to + task.intervals[j + 1].from) / 2, null]);
}
so I changed it to this
// add a null value between intervals
if (task.intervals[j + 1]) {
item.data.push({
task_id: interval.task_id,
x: (interval.to + task.intervals[j + 1].from) / 2,
y: null,
from: (interval.to + task.intervals[j + 1].from) / 2,
to: (interval.to + task.intervals[j + 1].from) / 2
});
}
here is the fixed plnkr
http://plnkr.co/edit/OEMuVfTMhHNQsTYGUyuy?p=preview
Please read this link to improve highcharts performance. A few months ago Highcharts released boost.js to improve chart performance with millions of data points.

Categories

Resources