我在一个名为render的函数中有下面的代码。如何在渲染函数外调用str变量值?
另外,请您解释下面的代码?我对js相当陌生,而且看着函数调用函数作为参数让我很伤心。
我的理解是app.getList是一个以函数作为参数的对象?但它没有返回任何东西。对不起,我迷失了。
app.getList("FieldList", function(reply){
var str = "";
$.each(reply.qFieldList.qItems, function(index, value) {
str += value.qName + ' ';
});
console.log(str);
});
完整代码:
define(["jquery",
//mashup and extension interface
"qlik",
//add stylesheet
"text!./css/mystyle.css",
"client.utils/state",
"client.utils/routing"
],
function($, qlik, cssContent, clientState, clientRedirect) {
/*-----------------------------------------------------------------*/
// function redirect (sheetId){
// clientRedirect.goToSheet(sheetId, Object.keys(clientState.States)[clientState.state])
// }
/*-----------------------------------------------------------------*/
/*-----------------------------------------------------------------*/
var render = function($elem, layout) {
var html = '',
app = qlik.currApp();
//get list of tab objects and insert into div
app.getAppObjectList('sheet', function(arrayitem) {
//for each sheet in the app, create a list item
$.each(arrayitem.qAppObjectList.qItems, function(myindex, myvalue) {
//include the sheet id as the list item id to be used as a reference for active sheet
html += '<li id="' + myvalue.qInfo.qId + '">'; // onClick="redirect(' + value.qInfo.qId + ');
//wrap anchor tag to be used by bootstrap styling
html += '<a>';
//give the link the same name as the sheet
html += myvalue.qData.title;
html += '</a>';
html += '</li>';
});
html += '</ul></div>';
html += "<button id='myButton'> Click Me!! </button>";
console.log(arrayitem.qAppObjectList);
console.log(html);
//insert html into the extension object
return $elem.html(html);
});
/* Test Code Start from here */
app.getList("FieldList", function(reply) {
var str = "";
$.each(reply.qFieldList.qItems, function(key, value) {
str += value.qName + ' ';
});
console.log(str);
});
};
/*-----------------------------------------------------------------*/
return {
/*-----------------------------------------------------------------*/
paint: function($element, layout) {
console.count();
/*-----------------------------------------------------------------*/
$(function() {
$element.html("#myButton").click(function() {
// for(var mynum = 1; mynum <= 5; mynum++){
// alert('button test' + mynum);
// };
});
});
/*-----------------------------------------------------------------*/
render($element, layout);
/*-----------------------------------------------------------------*/
}
};
});
&#13;
答案 0 :(得分:1)
app.getList
可能是异步(意味着它在后台运行)。您传递给它的功能是回调。一旦完成AJAX调用(或运行任何异步方法),该函数将在未来的某个时刻运行。
您的回调传递reply
,这是来自getList()
的“返回”值。您无法从此功能外部访问str
。您只需要在该函数中使用reply
和/或str
执行任何代码。