How to get golbal data in main.js file in Vue JS? - javascript

following code is from my main.js file. Here I am parsing data from a url using Vue object and it returns some array of data. Now, In the main.js file I have a another GraphChart object and here I need some data from tableData.
How it would be possible? or any other tricks ?
Now I am getting nothing.
var tableData = new Vue({
data: {
items: ''
},
methods: {
graphData: function () {
var self = this;
var testdata= '';
$.get( 'http://localhost:3000/db', function( data ) {
self.items = data;
});
},
},
created: function() {
this.graphData();
},
computed:{
});
new GraphChart('.graph', {
stroke: {
width: 24,
gap: 14
},
animation: {
duration: -1,
delay: -1
},
// series: needs data from ITEMS object
series:items._data.radialChart[1]
}
)

First, you would be able to get the data using tableData.items if you left the creation of the chart where it is. I expect there might be a problem with that though, because the data is retrieved asynchronously, meaning the chart will be created before the data is returned.
It looks like you will need to move the code that creates the chart into the callback that gets your data.
$.get("http://localhost:3000/db", function(data) {
self.items = data;
new GraphChart(".graph", {
stroke: {
width: 24,
gap: 14
},
animation: {
duration: -1,
delay: -1
},
series: self.items._data.radialChart[1]
});
});
Also, you could replace .graph with a Vue reference, but you didn't post your template, so I'm not sure where .graph appears in your template. You might also need to wrap the creation of GraphChart in $nextTick if you continue to use .graph, in which case the code would be
$.get("http://localhost:3000/db", function(data) {
self.items = data;
self.$nextTick(() => {
new GraphChart(".graph", {
stroke: {
width: 24,
gap: 14
},
animation: {
duration: -1,
delay: -1
},
series: self.items._data.radialChart[1]
});
});
});

Related

How to pass VueJS data to another script?

I'm converting an established site over to VueJS but hit a stumbling block on the best way to achieve this.
It's using D3-Funnel (https://github.com/jakezatecky/d3-funnel) to draw a funnel chart but how do I pass VueJS data variables to the charts constructor?
<script>
const data = [
{ label: 'Step 1', value: this.step1 },
{ label: 'Step 2', value: this.step2 },
.......
];
const options = {
block: {
dynamicHeight: true,
minHeight: 15,
},
};
const chart = new D3Funnel('#funnel');
chart.draw(data, options);
</script>
So I need to pass vue data variables into the values. My first thought is to move this into it's own function in the VueJS methods object and use the variables there using this.
Is there a better way of achieving this?
---------- Edit -------------
As per comments people wanted to see how I achieved this currently in vue. As already mentioned above I just created a function in the vue methods object and then call it.
methods : {
drawChart(){
const data = [
{ label: 'Step 1', value: 99999 },
{ label: 'Step 2', value: 9999 },
.......
];
const options = {
block: {
dynamicHeight: true,
minHeight: 15,
},
};
const chart = new D3Funnel('#funnel');
chart.draw(data, options);
}
},
mounted(){
this.drawChart();
}
Data is coming from an API and put into the vue data object.
data:{
step1: 0,
step2: 0,
....
},
methods:{
getData(){
axois.post......
response{
this.step1 = response.data.step1
this.step2 = response.data.step2
....
}
}
}
As I understand it you are trying to pass information down to a component and use it. If you are using single file components and webpack you can do something like this which is put together with examples listed on the vue website.
You can also take a look at this guys approach
App.vue
...
<my-d3-component :d3data="d3Data"></my-d3-component>
...
<script>
import d3Component from 'path/to/component'
var app = new Vue({
el: '#app',
data: {
d3Data: {}
},
components: {
'my-d3-component': d3Component
}
})
</script>
d3Component.vue
<template>
d3 html stuff goes here
</template>
<script>
export default {
props: ['d3Data'],
data() {
return {}
},
mounted: {
const options = {
block: {
dynamicHeight: true,
minHeight: 15,
},
};
const chart = new D3Funnel('#funnel');
chart.draw(this.d3Data, options);
}
}
</script>

cube portfolio with bootstrap template plugin not working

I am using cubeportfolio.js as part of a bootstrap template. It seems to be working but the custom .js part of the template is causing an error in the console.
The template I am using can be seen here, which is working without errors.
The error is 'Uncaught Error: cubeportfolio is already initialized. Destroy it before initialize again!'
For confidentiality reasons I can't post all the code but I have called the jquery.cubeportfolio.min.js at the bottom of the with the custom .js underneath.
Here is the custom .js
(function($, window, document, undefined) {
'use strict';
var gridContainer = $('#grid-container'),
filtersContainer = $('#filters-container'),
wrap, filtersCallback;
/*********************************
init cubeportfolio
*********************************/
gridContainer.cubeportfolio({
layoutMode: 'grid',
rewindNav: true,
scrollByPage: false,
defaultFilter: '*',
animationType: 'slideLeft',
gapHorizontal: 0,
gapVertical: 0,
gridAdjustment: 'responsive',
mediaQueries: [{
width: 800,
cols: 3
}, {
width: 500,
cols: 2
}, {
width: 320,
cols: 1
}],
caption: 'zoom',
displayType: 'lazyLoading',
displayTypeSpeed: 100
});
/*********************************
add listener for filters
*********************************/
if (filtersContainer.hasClass('cbp-l-filters-dropdown')) {
wrap = filtersContainer.find('.cbp-l-filters-dropdownWrap');
wrap.on({
'mouseover.cbp': function() {
wrap.addClass('cbp-l-filters-dropdownWrap-open');
},
'mouseleave.cbp': function() {
wrap.removeClass('cbp-l-filters-dropdownWrap-open');
}
});
filtersCallback = function(me) {
wrap.find('.cbp-filter-item').removeClass('cbp-filter-item-active');
wrap.find('.cbp-l-filters-dropdownHeader').text(me.text());
me.addClass('cbp-filter-item-active');
wrap.trigger('mouseleave.cbp');
};
} else {
filtersCallback = function(me) {
me.addClass('cbp-filter-item-active').siblings().removeClass('cbp-filter-item-active');
};
}
filtersContainer.on('click.cbp', '.cbp-filter-item', function() {
var me = $(this);
if (me.hasClass('cbp-filter-item-active')) {
return;
}
// get cubeportfolio data and check if is still animating (reposition) the items.
if (!$.data(gridContainer[0], 'cubeportfolio').isAnimating) {
filtersCallback.call(null, me);
}
// filter the items
gridContainer.cubeportfolio('filter', me.data('filter'), function() {});
});
/*********************************
activate counter for filters
*********************************/
gridContainer.cubeportfolio('showCounter', filtersContainer.find('.cbp-filter-item'), function() {
// read from url and change filter active
var match = /#cbpf=(.*?)([#|?&]|$)/gi.exec(location.href),
item;
if (match !== null) {
item = filtersContainer.find('.cbp-filter-item').filter('[data-filter="' + match[1] + '"]');
if (item.length) {
filtersCallback.call(null, item);
}
}
});
})(jQuery, window, document);
You have to destroy it before init:
gridContainer.cubeportfolio('destroy');
/*********************************
init cubeportfolio
*********************************/
gridContainer.cubeportfolio({
layoutMode: 'grid',
rewindNav: true,
scrollByPage: false,
defaultFilter: '*',
animationType: 'slideLeft',
gapHorizontal: 0,
gapVertical: 0,
gridAdjustment: 'responsive',
mediaQueries: [{
width: 800,
cols: 3
}, {
width: 500,
cols: 2
}, {
width: 320,
cols: 1
}],
caption: 'zoom',
displayType: 'lazyLoading',
displayTypeSpeed: 100
});
It is initialized somewhere else and therefore it throws an error because it doesn't know with which cubeportfolio() instance has to deal.
From the error output I’m pretty sure that you instantiate Cube Portfolio twice for the same element.
If you want to instantiate again the plugin call on that element the method destroy
jQuery('#my-grid').cubeportfolio('destroy');
and then the init method to instantiate again
jQuery('#my-grid').cubeportfolio(options);
If you need further help please send me a link to your website to check your code.

Using Angular.JS to bind a JSON value to a Syncfusion Circular gauge

I am working on a project using Syncfusion Javascript gauge control to display a weekly pay bonus. The data is stored on a SharePoint list. I wrote a javascript to convert the sharepoint list from XML to JSON.
<script type="text/javascript">
$ajax({
url: "/_api/web/lists/GetByTitle('bonusEntry')/items?$orderby=Date desc&$filter=Department eq 'Meltshop'&$top=1",
type: "GET",
headers: {
"accept":"application/json;odata=verbose",
},
success: function (data) {
var newMsBonus = "";
for(i=0; i < data.d.results.length; i++){
newMsBonus = newMsBonus + "<div>" + data.d.results[i].ACrew + "</div>";
}
$('#oDataanalysisScoreBoard').html(newMsBonus);
},
error: function (error) {
alert("error: " + JSON.stringify(error));
}
})
Then the value is placed in this Div.
<div id="oDataanalysisScoreBoard"></div>
Basically what I would like to do is bind the data to the Syncfusion control which is set up like this:
$("#CircularGauge1").ejCircularGauge({
width: 500,
height: 500,
backgroundColor: "#3D3F3D",
readOnly: false,
scales: [{
ticks: [{
type: "major",
distanceFromScale: 70,
height: 20,
width: 3,
color: "#ffffff"
}, {
type: "minor",
height: 12,
width: 1,
distanceFromScale: 70,
color: "#ffffff"
}],
}]
});
Then the gauge is created inside this:
<div id="CircularGauge1"></div>
The gauge will build but I cannot get the gauge to recieve the value.
If anyone has any ideas on how I can make this work or things I'm doing I would greatly appreciate any input! Thanks everyone!
EDIT:
The synfusion software creates a gauge and changes the needle based on a number value thats given to it. My ajax call pulls a number entered into a Sharepoint list and then displays that in a div.
In the above code snippet you mentioned the passing value as “String”. If you pass the string value to the loop it will concatenate as string value only. But we need to pass the integer value to the Circular Gauge properties(width, height, distancefromscale) to take effect. Hence, change the code snippet with the following.
$.ajax({
url: "/Gauge/GetData",
type: "POST",
success: function (data) {
var newMsBonus = 0;
for (i = 0; i < data.length; i++) {
newMsBonus = newMsBonus + data[i].MajorDistanceFromScale; // Here i have used the MajorScale distanceFromScale value for the demo
}
$('#oDataanalysisScoreBoard').html(newMsBonus);
},
failure: function (error) {
alert("no data available");
}
});
And we have prepared the sample to meet your requirement with the MVC application including the “.mdf” database. We have created the table called “GaugeData” and added the two record. And using the “$.ajax” called the action method “GetData” and received the “JSON” data from the controller. Refer the following code snippet.
View Page:
$.ajax({
url: "/Gauge/GetData",
type: "POST",
success: function (data) {},
failure: function (error) {
}
});
Controller Page:
public class GaugeController : Controller
{
GaugeDataDataContext db = new GaugeDataDataContext();
public JsonResult GetData()
{
IEnumerable data = db.GaugeDatas.Take(500);
return Json(data, JsonRequestBehavior.AllowGet);
}
}
And then assigned the calculated value to the gauge property. Here, I have used the “MajorDistanceFromScale” value read from the database record and assigned to the gauge properties. Refer the following coding snippet.
var distanceValue = parseInt($("#oDataanalysisScoreBoard")[0].innerHTML);
$("#CircularGauge1").ejCircularGauge({
width: 500,
height: 500,
backgroundColor: "#3D3F3D",
readOnly: false,
scales: [{
ticks: [{
type: "major",
distanceFromScale: distanceValue,
height: 20,
width: 3,
color: "#ffffff"
}, {
type: "minor",
height: 12,
width: 1,
distanceFromScale: 70,
color: "#ffffff"
}],
}]
});
And also please refer the below attached sample for more reference.
GaugeListSample

FuelUX datagrid not loading (using example)

I'm new to FuelUX so I was trying to get this to work, based on the example provided:
require(['jquery','data.js', 'datasource.js', 'fuelux/all'], function ($, sampleData, StaticDataSource) {
var dataSource = new StaticDataSource({
columns: [{property:"memberid",label:"LidId",sortable:true},{property:"name",label:"Naam",sortable:true},{property:"age",label:"Leeftijd",sortable:true}],
data: sampleData.memberdata,
delay: 250
});
$('#MyGrid').datagrid({
dataSource: dataSource,
stretchHeight: true
});
});
});
With this as the data:
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
} else {
root.sampleData = factory();
}
}(this, function () {
return {
"memberdata": [{
"memberid": 103,
"name": "Laurens Natzijl",
"age": "25"
}, {
"memberid": 104,
"name": "Sandra Snoek",
"age": "25"
}, {
"memberid": 105,
"name": "Jacob Kort",
"age": "25"
}, {
"memberid": 106,
"name": "Erik Blokker",
"age": "25"
}, {
"memberid": 107,
"name": "Jacco Ruigewaard",
"age":"25"
},{ /* etc */ }]
}
}));
I've got no console errors, no missing includes. Everthing works just fine - it even looks like it's loading. Except nothing shows up in the datagrid but '0 items'.
Any suggestions? I think I did everything the example provided...
EDIT: 14:33 (Amsterdam)
There seems to be a difference when I put this in console:
My page:
require(['jquery','data.js','datasource.js', 'fuelux/all'], function ($, sampleData, StaticDataSource) {
var dataSource = new StaticDataSource({
columns: [{property:"memberid",label:"LidId",sortable:true},{property:"name",label:"Naam",sortable:true},{property:"age",label:"Leeftijd",sortable:true}],
data: sampleData.memberdata,
delay: 250
});
console.debug(dataSource);
});
1st row in console:
function localRequire(deps, callback, errback) { /* etc */ }
2nd row in console:
StaticDataSource {_formatter: undefined, _columns: Array[3], _delay: 250, _data: Array[25], columns: function…}
FuelUX Example:
require(['jquery', 'sample/data', 'sample/datasource', 'sample/datasourceTree', 'fuelux/all'], function ($, sampleData, StaticDataSource, DataSourceTree) {
var dataSource = new StaticDataSource({
columns: [{property: 'toponymName',label: 'Name',sortable: true}, {property: 'countrycode',label: 'Country',sortable: true}, {property: 'population',label: 'Population',sortable: true}, {property: 'fcodeName',label: 'Type',sortable: true}],
data: sampleData.geonames,
delay: 250
});
console.debug(dataSource);
});
1st row in console:
StaticDataSource {_formatter: undefined, _columns: Array[4], _delay: 250, _data: Array[146], columns: function…}
2nd row in console:
function (deps, callback, errback, relMap) { /* etc */ }
Maybe this will help you help me :)
I didn't see all of the information I needed to provide a finite answer. The real magic is the datasource.js file (which you had not provided).
I thought an easier way of demonstrating all the necessary pieces would be to put together a JSFiddle showing your data in use and all the pieces that were necessary.
Link to JSFiddle of Fuel UX Datagrid sample with your data
Adam Alexander, the author of the tool, also has written a valuable example of using the dataGrid DailyJS Fuel UX DataGrid
// DataSource Constructor
var StaticDataSource = function( options ) {
this._columns = options.columns;
this._formatter = options.formatter;
this._data = options.data;
this._delay = options.delay;
};
StaticDataSource.prototype = {
columns: function() {
return this._columns
},
data: function( options, callback ) {
var self = this;
var data = $.extend(true, [], self._data);
// SEARCHING
if (options.search) {
data = _.filter(data, function (item) {
for (var prop in item) {
if (!item.hasOwnProperty(prop)) continue;
if (~item[prop].toString().toLowerCase().indexOf(options.search.toLowerCase())) return true;
}
return false;
});
}
var count = data.length;
// SORTING
if (options.sortProperty) {
data = _.sortBy(data, options.sortProperty);
if (options.sortDirection === 'desc') data.reverse();
}
// PAGING
var startIndex = options.pageIndex * options.pageSize;
var endIndex = startIndex + options.pageSize;
var end = (endIndex > count) ? count : endIndex;
var pages = Math.ceil(count / options.pageSize);
var page = options.pageIndex + 1;
var start = startIndex + 1;
data = data.slice(startIndex, endIndex);
if (self._formatter) self._formatter(data);
callback({ data: data, start: 0, end: 0, count: 0, pages: 0, page: 0 });
}
};
If you were to provide your markup and what your "datasource.js" file contains, I may be able to help you further.
I think the demonstration provides much information on any pieces you may not have understood.
Adding on to creatovisguru's answer:
In his JSFiddle example, pagination is broken. To fix it, change the following line:
callback({ data: data, start: start, end: end, count: count, pages: pages, page: page });
I had the exact same issue, when tried to integrate with Django. The issue I believe is on this line :
require(['jquery','data.js','datasource.js', 'fuelux/all'], function ($, sampleData, StaticDataSource) {
I was not able to specify file extension, my IDE (pycharm), would mark "red", when used "data.js", so it needs to stay without an extension, such as "sample/data"
What I end up doing to make it work, is downloading the full fuelux directory from github in /var/www/html on a plain Apache setup ( no django, to avoid URL.py issues for static files ) and everything works using their example. Here are the steps to get you started :
cd /var/www/html
git clone https://github.com/ExactTarget/fuelux.git
and you will end up with fuelux in /var/www/html/fuelux/
in your browser, navigate to : http://foo.com/fuelux/index.html ( assuming your default document root is /var/www/html )
good luck!

List and store binding... exact same data

I am using sencha to create a carousel which has multiple card panels. Each panel contains a list component that is attached to its own instance of a store.
All lists store instances call the same API to fetch the data but with different parameters.
Example:
Card 1, Has list 1 attached to Store 1 which calls mywebsite.com/api?node=1
Card 2, Has list 2 attached to Store 2 which calls mywebsite.com/api?node=2
Card 1 shows the right set of nodes retrieved from the API. But once i swipe to see card 2, both list 1 and list 2 show the exact same data although each one should have its own list od data.
Code:
Test.data.NodeStore = Ext.extend(Ext.data.Store, {
constructor : function(config) {
config = Ext.apply({
model: 'Test.models.Node',
autoLoad: false,
pageSize: 20,
proxy: {
type: 'scripttag',
url: Test.API.URL + '?action=getNodes',
extraParams: {
},
reader: {
type: 'json'
}
},
setSource: function(source) {
if(this.getProxy().extraParams.sourceID != source) {
this.getProxy().extraParams.sourceID = source;
}
}
}, config);
Test.data.NodeStore.superclass.constructor.call(this, config);
},
onDestroy : function(config) {
Test.data.NodeStore.superclass.onDestroy.apply(this, arguments);
}
});
Ext.reg('NodeStore', Test.data.NodeStore);
The list view:
Test.views.ListView = Ext.extend(Ext.Panel, {
sourceID: 0,
layout: {
type: 'vbox',
align: 'stretch'
},
items: [
{
xtype: 'list',
itemTpl : new Ext.XTemplate("<div class='node'>{title}</div>"),
store: Ext.create(Test.data.NodeStore, {}),
}
],
setSource: function(source) {
this.sourceID = source;
var store = this.items.get(0).getStore();
store.setSource(source);
store.load();
}
});
The main view which creates list views dynamically
Test.views.Viewer = Ext.extend(Ext.Carousel, {
indicator: false,
layout: 'card',
style: {
padding: '0 20px'
},
items: [
],
loadListView: function(listIndex) {
var currentRecord = Test.stores.ListStore.getAt(listIndex);
var newList = new Test.views.ListView();
newList.setSource(currentRecord.get('ID'));
this.add(newList);
this.doLayout();
},
initComponent: function() {
Test.views.Viewer.superclass.initComponent.apply(this, arguments);
loadListView(1);
loadListView(2);
}
});
This is really wierd... i am just wondering, is sencha assigning the exact same store, model, list component... don't know where to look
In the loadListView function, i had to create an object of store and assign it to the list dynamically rather than modifying existing store.
newList.items.get(0).store = Ext.create(Test.data.NodeStore, {});

Categories