FusionCharts not Updating in React - javascript

When trying to update a chart in React using the sample given by FusionCharts, I can't get the chart to update. It is definitely changing the value, which I found out by adding this line:
console.log(revenueChartConfigs.dataSource.data[2].value);
The value is changing from 590000 to 420000 as desired, but the chart does not update. Does anyone have advice on this? I have pasted my code below. Thanks.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="js/fusioncharts.js"></script>
<script type="text/javascript" src="js/fusioncharts.charts.js"></script>
<script type="text/javascript" src="js/fusioncharts.gantt.js"></script>
<script type="text/javascript" src="js/fusioncharts.maps.js"></script>
<script type="text/javascript" src="js/fusioncharts.powercharts.js"></script>
<script type="text/javascript" src="js/fusioncharts.ssgrid.js"></script>
<script type="text/javascript" src="js/fusioncharts.treemap.js"></script>
<script type="text/javascript" src="js/fusioncharts.widgets.js"></script>
<script type="text/javascript" src="js/fusioncharts.zoomscatter.js"></script>
<script src="https://unpkg.com/react#15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom#15/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/react-fusioncharts.min.js"></script>
<script type='text/babel'>
$(document).ready(function(){
var myDataSource = {
chart: {
caption: "Top 5 stores in last month by revenue",
subCaption: "Harry's SuperMart",
numberPrefix: "$",
theme: "fint"
},
data: [{
label: "Bakersfield Central",
value: "880000"
}, {
label: "Garden Groove harbour",
value: "730000"
}, {
label: "Los Angeles Topanga",
value: "590000"
}, {
label: "Compton-Rancho Dom",
value: "520000"
}, {
label: "Daly City Serramonte",
value: "330000"
}]
};
var RevenueChart = React.createClass({
/**
** `getInitialState()` method is used to initialize the state of the
** the `RevenueChart` component.
**/
getInitialState: function () {
return {
eventTarget: ''
};
},
/**
** The `handleClick()` function is defined in the `RevenueChart` component.
** This function is configured to store the state of the `eventTarget` using
** the `setState()` method of React. This is binded to button click.
**/
handleCLick: function () {
this.setState({
eventTarget: 'btn-update-data'
});
},
render: function () {
var revenueChartConfigs = {
id: "revenue-chart",
renderAt: "revenue-chart-container",
type: "column2d",
width:600,
height: 400,
dataFormat: "json",
dataSource: myDataSource,
eventTarget: this.state.eventTarget,
impactedBy: ['btn-update-data']
};
/**
** Using the state, we update the `label` and `value` for the third and
** fourth data plots in the `render()` method of RevenueChart. The configuration
** object that is passed as props is used to refer to the `label`
** and `value` attributes of the `data` object array.
**/
if (this.state.eventTarget && this.state.eventTarget.length != 0) {
revenueChartConfigs.dataSource.data[2].label = "Art Supply Store";
revenueChartConfigs.dataSource.data[2].value = "420000";
revenueChartConfigs.dataSource.data[3].label = "P.C. Richard & Son";
revenueChartConfigs.dataSource.data[3].value = "320000";
}
else {
revenueChartConfigs.dataSource = myDataSource;
}
console.log(revenueChartConfigs.dataSource.data[2].value);
return (
<div>
/** The `FusionCharts` React component is used to render the chart. **/
<react_fc.FusionCharts {...revenueChartConfigs} />
/** Create a button, which when clicked will call the `handleClick()` function. **/
<a id='btn-update-data'
onClick={this.handleCLick}
className="btn btn-default"
href="#">{'Click me to change data'}</a>
</div>
);
}
});
ReactDOM.render(
<RevenueChart />,
document.getElementById('chart-container')
);
});
</script>
</head>
<body>
Hello
<div id="chart-container"></div>
</body>
</html>

Related

How to disable the initial values in a kendo mvc multiselect, so they wont be unselected?

I'm trying to have a kendo multiselect filled with some initial values which can't be removed later by the user.
I've tried to run through the DataBond event of multiselect widget and get each of the elements, but I couldn't accomplish what I'm trying.
Maybe (or more probably) I'm doing something wrong.
Also, I've seen this to disable elements:
<span class="#: unselectableItem ? 'k-state-disabled': ''#">
#: text #
</span>
But i'm not sure, how to implement it.
What I have so far:
#(Html.Kendo().MultiSelect().Name("msEquipoResponsable")
.DataValueField("Id").DataTextField("Tipo")
.DataSource(ds => ds.Read(r => r.Action("ObtenerPersonal","AuditoriaPlaneacionMemorandoEditor")))
.Value(Model.EquipoResponsable.Split(','))
.Events(ev => ev.DataBound("onBindingMS"))
)
DataBound function:
function onBindingMS(event)
{
var dataItems = event.sender._dataItems;
$.each(dataItems, (ind, el) => {
//Disabled logic should be here i guess...
});
}
Try preventing the deselect event to be completed using e.preventDefault() for those items which cannot be deselected.
deselect: function(e) {
if (e.dataItem.unselectableItem)
{
// Call preventDefault() to prevent the deselection
e.preventDefault();
}
}
In the snippet below, items Item1 and Item3 starts selected and cannot be deselected according to the unselectableItem property:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.common.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.default.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.mobile.all.min.css">
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/angular.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/jszip.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/kendo.all.min.js"></script></head>
<body>
</body>
<select id="multiselect" multiple="multiple">
<option selected>Item1</option>
<option>Item2</option>
</select>
<script id="item-template" type="text/x-kendo-template">
<span class="#: unselectableItem ? 'k-state-disabled': ''#">
#: text #
</span>
</script>
<script>
$("#multiselect").kendoMultiSelect({
dataSource: [{
id: 1,
text: "Item1",
unselectableItem: true
},{
id: 2,
text: "Item2",
unselectableItem: false
},{
id: 3,
text: "Item3",
unselectableItem: true
},{
id: 4,
text: "Item4",
unselectableItem: false
}],
dataValueField: "id",
itemTemplate: $("#item-template").html(),
tagTemplate: $("#item-template").html(),
deselect: function(e) {
if (e.dataItem.unselectableItem)
{
// Call preventDefault() to prevent the deselection
e.preventDefault();
}
},
value: [1,3]
});
</script>
</html>
Demo

Moment.js date conversion is not working with DataTable

I have a DataTable that contains dates that are formatted like this: "/Date(1185336000000)/".
In the following code, I followed DataTable's docs to integrate Moment.js for date conversion---either I'm missing something or my code is written incorrectly. Or both.
Any thoughts on this? I believe part of the issue lies with function loadPH, but I don't want to remove it.
JS snippet:
import $ from 'jquery';
import admissData from '../JSON/sk-admiss.json';
import DataTable from 'datatables.net';
import moment from 'moment';
function loadPH() {
let admissText = admissData.d.results
.filter(x => x.p_h_v !== "")
.map(function(val) {
return {
"PH": val.p_v_h,
"Stuff": val.stuff,
...
...
"Date of Admission": val.dateofadmission,
... // ----- irrelevant info
}
})
$.fn.DataTable.moment('MMM Do YY'); // ---- console error: "default.a.fn.DataTable.moment is not a function"
$('#prohac-table').DataTable({
columns: [
{ data: "PH" },
{ data: "Stuff" },
...
...
{ data: "Date of Admission" },
... // ----- irrelevant info
],
columnDefs: [{
type: 'date',
targets: [4]
}],
data: admissText
});
}
loadPH();
HTML snippet:
<script src="index.js"></script>
<script
src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js" integrity="sha384-7aThvCh9TypR7fIc2HV4O/nFMVCBwyIUKL8XCtKE+8xgCgl/PQGuFsvShjr74PBp" crossorigin="anonymous"></script>
<script
src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
<script
src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script
src="//cdn.datatables.net/plug-ins/1.10.12/sorting/datetime-moment.js"></script>
Update: I did some digging and the solution involved working with columnDefs:
{ data: "x" },
{ data: "y" },
{ data: "z" },
{ data: "zz" },
{ data: "Date of Admission" }, // ----- target
...
{ data: "Classification" }
],
columnDefs: [
{"type":"unix","targets":4,"render": function(data) {
return moment.utc(data, "x").format('MM/DD/YYYY')
}}, // targets must be plural
],
Here is how I would process the strange date format "/Date(1185336000000)/" which I assume to be a Unix time stamp in milliseconds.
First, remove that line from your code: $.fn.DataTable.moment('MMM Do YY');
Then, processStrangeDate() (Feel free to rename it as you like) would be a function to retreive the Unix timestamp and convert it using Moment.js
function parseDate(strangeDate){
return moment(parseInt(strangeDate.split("(")[1])).format('MMM Do YY');
}
Here is a simple demo:
var strangeDate = "/Date(1185336000000)/";
// A function to process that strange date format
function processStrangeDate(strangeDate){
return moment(parseInt(strangeDate.split("(")[1])).format('MMM Do YY');
}
// Processing example
var strangeDate = "/Date(1185336000000)/";
console.log(processStrangeDate(strangeDate));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
And how to use it in DataTables:
// A function to process that strange date format
function processStrangeDate(strangeDate){
return moment(parseInt(strangeDate.split("(")[1])).format('MMM Do YY');
}
// Example in dataTables using columnDef
$("#example").dataTable({
data:[
["Line 1","/Date(1185336000000)/","/Date(1185336000000)/"]
],
columnDefs:[
{
targets:2, render: function(data){ // Target is the column # zero-based
return processStrangeDate(data);
}
}
]
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js" integrity="sha384-7aThvCh9TypR7fIc2HV4O/nFMVCBwyIUKL8XCtKE+8xgCgl/PQGuFsvShjr74PBp" crossorigin="anonymous"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="//cdn.datatables.net/plug-ins/1.10.12/sorting/datetime-moment.js"></script>
<!-- Above is your CDN calls untouched... I just added some CSS below -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/css/jquery.dataTables.css" rel="stylesheet"/>
<table id="example">
<thead>
<th>Something</th>
<th>Strange Date</th>
<th>Processed Date</th>
</thead>
<tbody>
</tbody>
</table>
CodePen

Uncaught ReferenceError: characters is not defined

I am creating a simple rest api in javascript, I want upon initialization, the widget must display a list of all characters.
here is folder structure :
├───book
└───book.js
├───store
│ └───store.js
here is my store.js
window.Store = {
create: function() {
var self = {};
var props = {
name: 'string',
species: 'string',
picture: 'string',
description: 'string'
};
var listProps = ['name', 'species'];
var detailProps = ['name', 'species', 'picture', 'description'];
var characters = [
{
id: makeID(),
name: 'Ndiefi',
species: 'Wookie',
picture: 'store/img/ndiefi.png',
description: 'A legendary Wookiee warrior and Han Solo’s co-pilot aboard the Millennium Falcon, Chewbacca was part of a core group of Rebels who restored freedom to the galaxy. Known for his short temper and accuracy with a bowcaster, Chewie also has a big heart -- and is unwavering in his loyalty to his friends. He has stuck with Han through years of turmoil that have changed both the galaxy and their lives.',
_delay: 500
},
];
}
}
here is index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Character Book</title>
<!-- 3rd party vendor libraries -->
<link rel="stylesheet" href="vendor/font-awesome-4.6.3/css/font-awesome.min.css">
<script src="vendor/jquery-3.1.0.min.js"></script>
<script src="vendor/underscore-1.8.3.min.js"></script>
<!-- 1st party internal libraries -->
<script src="store/store.js"></script>
<script src="tests/start-test.js"></script>
<script src="tests/test-book.js"></script>
<!-- The source of the 'Book' widget -->
<link href="book/book.css" rel="stylesheet">
<script src="book/book.js"></script>
<script>
$(function() {
var frame = $('#test-frame');
var run = $('#test-run');
var results = $('#test-results');
var store = Store.create();
run.click(function() {
run.prop('disabled', true).text('Running Tests');
results.removeClass('test-pass test-fail').text('');
testBook(frame).then(
function success() {
run.prop('disabled', false).text('Run Tests');
results.addClass('test-pass').text('All tests passed');
},
function failure(err) {
run.prop('disabled', false).text('Run Tests');
results.addClass('test-fail').text('Test failed, see console');
}
);
});
Book.init(frame, store);
});
</script>
</head>
<body>
<button id="test-run">Run Tests</button>
<span id="test-results"></span>
<div id="test-frame">
</div>
</body>
</html>
here is what I have tried :
books.js
var data = JSON.parse(characters);
data.forEach(characters => {
console.log(characters.name)
});
so when I run the app in my browser I see the following error :
Uncaught ReferenceError: characters is not defined
what is wrong with my code ? any suggestion or help will be helpfull thanks

modifying data variable in vue.js using axios

Here is my script :
<html>
<script src="https://unpkg.com/vue"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.0/axios.js"></script>
<body>
<div id="app-3">
<span v-if="seen">{{ textFromApi }}</span>
</div>
<br/>
<script type="text/javascript">
var app3 = new Vue({
el: '#app-3',
data: {
seen: true,
textFromApi: "hello"
},
methods: {
getData() {
return axios.get('https://jsonplaceholder.typicode.com/posts/1')
},
},
created: function () {
this.textFromApi = this.getData();
}
})
</script>
</body>
</html>
I'm trying to modify this.textFromApi from the call of this api: https://jsonplaceholder.typicode.com/posts/1
but my this.textFromApi doesn't seems to update, any ideas why?
Here is a fiddle code:
https://jsfiddle.net/bussiere/5t3v013o/
Edited from remark just below
Regards and thanks
created() is a lifecycle hook, it should be at the same level as data, methods, computed etc. Not a child of methods (so if you nest created() in methods() it will never get executed unless you call the method).
You also don't do anything with the axios promise, you should process it using then ().
<script src="https://unpkg.com/vue"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.0/axios.js"></script>
<body>
<div id="app-3">
<span v-if="seen">{{ textFromApi }}</span>
</div>
<br/>
<script type="text/javascript">
var app3 = new Vue({
el: '#app-3',
data () {
return {
seen: true,
textFromApi: { title: 'empty'}
}
},
methods: {
getData() {
return axios.get('https://jsonplaceholder.typicode.com/posts/1').then(response => {
this.textFromApi = response.data
})
},
},
created: function () {
this.getData();
}
})
</script>
</body>
</html>

example works in js-fiddle but not in self-made page

This js-fiddle example is working as it should:
https://jsfiddle.net/qf089a0a/51/
But when I try to load this example on my own, the dropdown menu doesn't show anything -- even though it does in the js-fiddle example (try entering "wireless" in the input box.)
This is my html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.18/vue.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id="app">
<input v-model="offer.tags"></input>
<select>
<option v-for="(key, value) in offer.units" v-bind:value="offer.units">
{{ key }}
</option>
</select>
</div>
</body>
<script src="./js/app.js"></script>
</html>
And here is the js:
var protocol = {
"wireless": {
"units": {
"bandwidth": "bit/s, Mb/s, Gb/s",
"distance": "kilometers, miles"
},
"children": [],
}
};
var vm = new Vue({
el: '#app',
data: {
offer: {
tags: '',
units: {}
},
protocol: protocol
},
watch: {
'offer.tags': {
handler: function() {
var tagList = this.offer.tags.split(',');
console.log(tagList);
for (var i = 0; i < tagList.length; i++) {
console.log(tagList[i]);
try {
var unitsObj = this.protocol[tagList[i]]["units"];
var unitKeys = Object.keys(unitsObj);
for (var i = 0; i < unitKeys.length; i++) {
if (!unitsObj[unitKeys[i]]) {
console.log("updating units");
// update dict only if it doesn't already contain key
this.offer.units[unitKeys[i]] = unitsObj[unitKeys[i]];
}
this.offer.units[unitKeys[i]] = unitsObj[unitKeys[i]];
}
console.log(this.offer.units);
} catch (e) {
return true
}
}
}
}
}
});
Any ideas as to what could be the problem?
Here's what the console prints out in the offline version - it's the same as the online version:
Array [ "wireless" ]
app.js:27:9
wireless
app.js:30:11
Object { bandwidth: "bit/s, Mb/s, Gb/s", distance: "kilometers, miles", 1 more… }
So, apparently the dictionary is being updated as I expect.
The Problem is the Version of Vue JS you are using. the one you mentioned here is different and the one you are using in jsfiddle is different.
Please remove the one u mentioned here and add the following.
<script type="text/javascript" src="https://unpkg.com/vue#2.0.3/dist/vue.js"></script>
It will work fine.

Categories

Resources