I've got a function changeGraph() inside the jQuery-wrapper which I need to call somehow from outside it. I need to access the function setData from the jQuery based graph-library Flot.
The source is looking like this:
function changeGraph(){
// I need to access $.plot.setData somehow
};
var d2 = [[0, 0], [20, 300000]];
$(function () {
$.plot($("#placeholder"),
[{color: "#000000", data: d2}],
{
series: {
lines: { show: true, fill:true, fillColor: {colors: [ "#d1ddea","#8e959d"]}},
points: { show: false }
}
}
);
});
How can I accomplish this?
var changeGraph;
$(function () {
changeGraph = function () {
// Need to access $.plot($("#placeholder") here
};
});
changeGraph(); // call this when document is ready at least
You should move your function outside of the callback function.
function changeGraph() {
// ...
}
$(function() {
changeGraph();
});
Related
I am using ChartJS to create a chart on a page in angular. I am running into the issue of when I navigate to a new page, and back to the original page, the JS is not called again.
Is there a way to call a javascript function or file every time an angular page navigates? I guess I'd then just see if my selector exists on the page and then call the function.
$(document).ready(function () {
//Call on every page:
(function ($) {
$(window).load(function () {
$(".bubbleScrollbar").mCustomScrollbar({
theme: "rounded-dots"
});
$(".hBubbleScrollbar").mCustomScrollbar({
//theme: "minimal-dark",
theme: "rounded-dots-dark",
axis: "x",
advanced: {autoExpandHorizontalScroll: true},
mouseWheelPixels: 150
});
});
})(jQuery);
// on all chart pages:
var ctx = $('#chart-TicketsResolved').get(0).getContext("2d");
var data = [
{
value: 300,
color: "#50AD7E",
label: "Resolved"
},
{
value: 200,
color: "#d9d9d9",
label: "Open"
}
];
var myDoughnutChart = new Chart(ctx).Gauge(data);
});
You can call your function by listenning to window.hashchanged event.
window.onhashchange = function () {
console.log('my function runs every time the # hash changes');
}
See more here: How to detect URL change in JavaScript
I'm using Google Charts API and i'm getting a issue which i cant understand. All code works well if i use the final alert("Im IN!"), but if i remove it my nArray is not filled. and i dont understand why.
This are global vars:
var Chart;
var data;
var nArray;
This is where i fill my nArray so i can load into my chart.
function setArray(PlayerName,LeadPoints,OppPoints,PropPoints){
var newPlayer = [PlayerName,LeadPoints,PropPoints,OppPoints,'Total'];
nArray.push(newPlayer);
}
This is where i go to CRM to bring data to and fill my array calling the setArray function.
function setPointsByEntity() {
SDK.REST.retrieveMultipleRecords(
"gamify_ponto",
"$select=gamify_Entidade,gamify_PlayerId,gamify_Pontos,gamify_gamify_utilizador_gamify_ponto/gamify_name&$orderby=gamify_PlayerId asc&$expand=gamify_gamify_utilizador_gamify_ponto",
function (results) {
if(results.length>0){
for(var i=0;i<results.length;i++){
(...) // do something
setArray(lastPlayer.Name,leadPoints,oppPoints,propPoints);
}
}
else {
alert("No Contact records are available to set as the primary contact for the account.");
}
},
errorHandler,
function () {
//OnComplete handler
}
);
This is where i load Visualization API, run google visualization, and define my drawVisualization function.
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// Create and populate the data table.
data = google.visualization.arrayToDataTable(nArray);
setLabelTotal(data);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, 2, 3, {
type: 'number',
calc: function (dt, row) {
// set offset to determine how far you want to move the labels
var offset = MaxArray(nArray) *0.03; // 3% do valor total.
return dt.getValue(row, 1) + dt.getValue(row, 2) + dt.getValue(row, 3) + offset;
}
},
4]);
var options = {title:"Pontos por Jogador",
width:500, height:300,
hAxis: {
textStyle: {'color': 'white'}},
isStacked: true,
legend: {
position: 'top'
},
series: {
3: {
type: 'line',
color: 'grey',
lineWidth: 0,
pointSize: 0,
visibleInLegend: false
}
},
vAxis: {
viewWindowMode:'explicit',
viewWindow: {
max:MaxArray(nArray) + MaxArray(nArray)*0.3,
min:0
}
},
animation:{
duration: 1000,
easing: 'linear'}
};
// Create and draw the visualization.
chart = new google.visualization.ColumnChart(document.getElementById('visualization'));
chart.draw(view, options);
}
Finally when dom is ready i assign my nArray by invoking setPointsByEntity(). The problem here is if i comment the "alert("Im IN!");" Chart wont appear. It seems that the nArray is not define.
// whenever the dom is ready
$(document).ready(function()
{
setPointsByEntity(); // This function fill my nArray
alert("Im IN!");
});
This question it may have to do with another one that i've posted before, please follow this Question
Move the setPointsByEntity from the document ready handler to a callback from the google loader, and then call the drawVisualization function at the end of the success handler of the AJAX call:
google.setOnLoadCallback(setPointsByEntity);
function setPointsByEntity() {
SDK.REST.retrieveMultipleRecords(
"gamify_ponto",
"$select=gamify_Entidade,gamify_PlayerId,gamify_Pontos,gamify_gamify_utilizador_gamify_ponto/gamify_name&$orderby=gamify_PlayerId asc&$expand=gamify_gamify_utilizador_gamify_ponto",
function (results) {
if(results.length>0){
for(var i=0;i<results.length;i++){
(...) // do something
setArray(lastPlayer.Name,leadPoints,oppPoints,propPoints);
}
}
else {
alert("No Contact records are available to set as the primary contact for the account.");
}
drawVisualization();
},
errorHandler,
function () {
//OnComplete handler
}
);
}
If I run a test case like this, my test results show up inside the YUI test-console widget:
YUI({debug: true}).use('test', 'event-base', 'test-console', function (Y) {
fooTests = new Y.Test.Case({
name: "foo",
testFoo: function () {
Y.assert(5 == 6);
}
});
Y.on("domready", function () {
(new Y.Test.Console({
newestOnTop: false,
style: 'block'
})).render('#log');
Y.Test.Runner.add(fooTests);
Y.Test.Runner.run();
});
});
If I run the exact same code but create another YUI instance that uses 'test' first, the tests show up in the browser javascript console (if it's open).
YUI({debug: true}).use('test', function (Y) {
});
YUI({debug: true}).use('test', 'event-base', 'test-console', function (Y) {
fooTests = new Y.Test.Case({
name: "foo",
testFoo: function () {
Y.assert(5 == 6);
}
});
Y.on("domready", function () {
(new Y.Test.Console({
newestOnTop: false,
style: 'block'
})).render('#log');
Y.Test.Runner.add(fooTests);
Y.Test.Runner.run();
});
});
Is there a way to get the results to show up in the test-console widget when 'test' is used by another YUI instance?
I found the answer here.
I had to add
logSource: Y.Global
To Test.Console's parameter object.
(new Y.Test.Console({
logSource: Y.Global,
newestOnTop: false,
style: 'block'
})).render('#log');
connectLoadRenderStoreAndGetCheckBox: function () {
this.someStore = new Ext.data.Store({
proxy:
reader:
]),
sortInfo: { field: , direction: }
});
this.someStore.load(
{
params:
{
}
});
//I left out parameters; lets assume they are valid and work.
this.someStore.on("load", this._renderColumns, this);
return ([this._getCheckBox()]);
}
On 'load' I want to both execute the function this._renderColumns (which uses the data from the server) and also return a checkbox (which also uses data from the server).
What is a quick & easy way to only return the checkbox after the data is loaded?
_getCheckBox: function () {
if (UseDefault == "y") {
return new Ext.form.Checkbox(
{
fieldLabel:,
itemCls:,
checked: true,
labelStyle:
});
}
else {
return new Ext.form.Checkbox(
{
fieldLabel:,
itemCls:,
checked: false,
labelStyle:
});
}
},
_renderColumns: function () {
var record2 = this.something.something2(2);
UseDefault = record2.get("UseDefault");
}
I have a onclick event that has a value in it that I want to post to a backend php script. Just not sure how to get it in the dialog function.
function reorder(job_index)//<--------this fella
{
$('#dialog').dialog('open');
}
$(document).ready(function(){
$(function() {
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 250,
width: 600,
modal: true,
buttons: {
'Yes, use the number above': function() {
var jobID=$("#jobnumber").val();
$.post("rpc.php", {
job_index:job_index,// <-------to here
jobID:jobID,
method: "reorder"
},
function(data,textstatus)
{
alert(data.message);
}, "json");
},
'No, create a new number for me': function() {
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
});
});
});
The value is job_index. Any tips?
Thanks
In the below code, I'm using a single function that will allow you to both store and retrieve your index.
The function index is creating a closure by returning declaring and returning another function. This means that the variable _index will still be available (think of it as like the variable was allocated on the heap instead of the stack-frame; ie malloc-ed) once the (outer) function has returned, and as you can see the function is self-invoking, due to the }(); on the last line of the function, thus returning immediately during parsing.
Then when you call the function index again (which now you will be basically calling the inner function that takes one formal argument, ind), you can pass in your index and if you do, the function will store it in the _index variable that I mentioned earlier on...ie the variable that is still available after the outer function returned.
If you don't pass in an argument (ie invoke the function like such: index()), the function only returns your stored variable. The logic behind this is that if a parameter is not passed, the value of the actual argument is undefined. Thus the function checks if the value is undefined, and if it is, it justs returns your variable.
And btw, you have a nested ready function inside your outer ready function. This is because $(function() { is the same as $(document).ready(function(){. I fixed this in the below code:
var index = function () {
var _index;
return function (ind) {
if (typeof ind !== "undefined") {
_index = ind;
}
return _index;
};
}();
function reorder(job_index)
{
index(job_index);
$('#dialog').dialog('open');
}
$(function () {
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 250,
width: 600,
modal: true,
buttons: {
'Yes, use the number above': function () {
var jobID = $("#jobnumber").val();
$.post("rpc.php", {
job_index: index(),
jobID: jobID,
method: "reorder"
},
function (data, textstatus) {
alert(data.message);
},
"json");
},
'No, create a new number for me': function () {
$(this).dialog('close');
},
Cancel: function () {
$(this).dialog('close');
}
}
});
});
Another way to do it is by using the data method that nickf mentioned. This will allow you to store the index directly as part of your element, like such:
function reorder(job_index)
{
$('#dialog').data("job", job_index).dialog('open');
}
$(function () {
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 250,
width: 600,
modal: true,
buttons: {
'Yes, use the number above': function () {
var jobID = $("#jobnumber").val();
$.post("rpc.php", {
job_index: $("#dialog").data("job"),
jobID: jobID,
method: "reorder"
},
function (data, textstatus) {
alert(data.message);
},
"json");
},
'No, create a new number for me': function () {
$(this).dialog('close');
},
Cancel: function () {
$(this).dialog('close');
}
}
});
});
You could store it as data on the element using .data()
Create a global variable, store the last clicked job_index there, and read it from there in the click handler.
var last_job_index;
function reorder(job_index)
{
last_job_index = job_index;
$('#dialog').dialog('open');
}
//snip
$.post("rpc.php", {
job_index: last_job_index,
jobID: jobID,
method: "reorder"
},
Warning: This is quite an unprofessional solution (shared mutable state)