我有一个像这样的设定间隔函数 -
setInterval(function(){
var postData = {'some json data'};
var successCallback = function(data) {
console.log(data);
}
var errorCallback = function(data) {
console.log(data);
}
RestClient.invokeRemoteService(postData, this.successCallback, this.errorCallback);
}, 10000);
以下是我在invokeRemoteService()
处的RestClient
方法(在另一个档案中) -
RestClient = window.RestClient || {};
(function (w, rs) {
rs.invokeRemoteService = function ( postData, successCallBack, errorCallBack){ //label-1, successCallback and errorCallback are undefined
$.ajax({
url : '/some/url/',
dataType : "json",
data :{
cmd: ko.toJSON(postData)
},
type : "post",
async : true,
success : function(data) { //label-2, get data ok
if (typeof successCallBack === "function") { //label-3, successCallBack is undefined
successCallBack(data); //label-4
}
},
error : function() {
if (typeof errorCallBack === "function") {
errorCallBack(); //label-5
}
}
});
};
})(window, RestClient);
但是当我从RestClient.invokeRemoteService()
方法调用setInterval()
方法时,successCallback
和errorCallback
label-1
label-3
label-5
总是'未定义'和label-2. The
。
虽然服务调用完美,但我在work fine for other. But when I call it from
RestClient.invokeRemoteService()const sudoku = [
[1, 2, 3, 4],
[3, 4, 1, 2],
[2, 3, 4, 1],
[4, 1, 2, 3]
]
class SudokuChecker {
getCheckList (length) {
const nums = {}
for (let i=1; i<=length; i++) nums[i] = 0
return nums
}
isCorrect (list) {
const checkList = this.getCheckList(list.length)
list.forEach(num => checkList[num]++)
return Object.values(checkList).every(x => x == 1)
}
getRow (matrix, row) {
return matrix[row]
}
getColumn (matrix, col) {
return matrix.map(row => row[col])
}
getBox (matrix, box) {
const procNum = Math.sqrt(matrix.length)
// given some box ID number (starting at 0), all I need :
// a) index of that box's top row
const topRow = 'find_me' // calculated with "box" and procNum somehow...
// b) the index of that box's first num at that row.
const sliceFrom = 'find_me' // no idea at the moment how to calculate...
let boxNums = []
for (let i=0; i<procNum; i++) {
boxNums = boxNums.concat(matrix[topRow + i].slice(sliceFrom, sliceFrom + procNum))
}
return boxNums
}
checkLists (matrix, type, unit=0) {
const pass = this.isCorrect(this['get'+type](matrix, unit))
if (!pass) return false
if (unit == matrix.length-1) return pass
return this.checkLists(matrix, type, ++unit)
}
checkAll (matrix) {
const types = ['Row', 'Column', 'Box']
return types.map(t => this.checkLists(matrix, t)).every(x => x === true)
}
}
setInterval()`得到了正确的数据。请帮忙。
答案 0 :(得分:2)
不需要this
,您的successCallback
和errorCallback
直接在范围内。
setInterval(function(){
var postData = {'some json data'};
var successCallback = function(data) {
console.log(data);
}
var errorCallback = function(data) {
console.log(data);
}
RestClient.invokeRemoteService(postData, successCallback, errorCallback);
}, 10000);