我已经定义了一个全局变量,然后将其设置为通过我的一个模块提供的方法,该模块可以呈现图表。模块应该返回一个图表,从而为变量'alChart'指定一个图表对象。还值得一提的是,该图表使用此代码完全正常。
图表渲染模块:
var ChartRendererGateway = (function ($, Highcharts) {
"use strict";
//Private variables
var chart;
var result;
//Private methods
var success = function (data, textStatus, jqXHR) {
var seriesObject = $.parseJSON(data);
result = seriesObject;
};
var fail = function () {
errorController.showError("Something went wrong when trying to load the chart data")
};
var drawChart = function (renderTo, options) {
options.chart.renderTo = renderTo;
options.series = result;
chart = new Highcharts.Chart(options);
};
//Public methods
return {
render: function (renderTo, promise, options) {
promise.then(success, fail)
.done(function () {
drawChart(renderTo, options);
})
.fail(function () {
errorController.showError("Something went wrong fetching chart data!");
});
return chart; //Chart object exists here, but is undefined when inspecting variable it is assigned to in the .ready function
},
destroy: function(chartName){
chartName.destroy();
}
};
})(jQuery, Highcharts);
。就绪():
//Global Variables
var alChart;
//DOM Ready
$(function () {
var chartData = ChartDataGateway.getSeries("/Dashboard/GetAssetLiabilityChartData");
alChart = ChartRendererGateway.render("dashboard-AL-chart", chartData,
{
chart: {
type: 'line',
zoomType: 'xy'
},
title: {
text: null
},
xAxis: {
title: {
text: 'Date'
},
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
yAxis: {
title: {
text: 'Amount'
}
},
credits: {
enabled: false
},
plotOptions: {
line: {
allowPointSelect: true,
cursor: 'pointer',
marker: {
enabled: true,
radius: 1,
symbol: 'circle',
states: {
select: {
fillColor: '#fff',
radius: 4,
halo: {
size: 4,
attributes: {
'stroke-width': 1,
stroke: '#003f72'
}
}
}
}
}
}
}
});
console.log(alChart); //This is returning 'undefined' and NOT the chart object WHY?! :S
});
答案 0 :(得分:2)
我之前没有做过jQuery承诺,但我对此有所了解。为了链接值,我认为你需要在jQuery的每一步创建新的promise(如果你这样做.then()。then()你会在每个中获得相同的数据,而不是从前一个.then()返回的数据。 。因此,每当您需要新数据并处理异步事件时,如果您要更改数据并希望进一步更改数据,则需要创建一个新的承诺,以便每次都链接。
这是一个如何在基本形式中实现所需目标的示例:
function doSomething() {
var deferred = jQuery.Deferred();
// Asynchronous action
setTimeout(function() {
deferred.resolve("some data");
}, 1000);
return deferred.promise();
}
function doSomethingElse() {
var deferred = jQuery.Deferred();
// Has to wait for asynchronous action
doSomething()
.then(function(data) {
console.log(data); // Should be "some data"
deferred.resolve(data + " that's been added to");
})
;
return deferred.promise();
}
// Waits for everything to be done that's above, then console.logs end result
doSomethingElse()
.then(function(data) {
console.log(data); // Should be "some data that's been added to"
})
;
您可以在此处查看此操作:http://jsbin.com/getiludexe/2/edit?js,console