1
我一直在使用knockout.js一段時間,並且之前沒有遇到過這個問題。通常情況下,當我試圖推動新的JS對象的observableArray,它的工作原理沒有問題,但由於某些原因,這一次我得到這個錯誤:knockout.js observableArray不被識別爲函數
TypeError: self.Students.push is not a function
這裏是我的代碼片段:
window.ApiClient = {
ServiceUrl: "/api/students",
Start: function() {
var viewModel = ApiClient.ViewModel(ngon.ClientViewModel);
ko.applyBindings(viewModel);
viewModel.get();
}
};
ApiClient.ViewModel = function(data) {
var self = this;
ko.mapping.fromJS(data, {}, this);
this.get = function (id) {
if (id == undefined) {
return ApiClient.Service.get(self.PageSize(), self.PageNumber(), function (data) {
self.Students(data);
});
}
}
this.post = function() {
return ApiClient.Service.post(self.DetailedStudent, function (data) {
self.Students.push(data);
});
}
return this;
}
ApiClient.Service = function() {
var _get = function (pageSize, pageNumber, callback) {
sv.shouldShowLoading = false;
var queryParams = String.format("?pageSize={0}&pageNumber={1}", pageSize, pageNumber);
$.ajax(ApiClient.ServiceUrl + queryParams, {
dataType: "json",
type: "get",
success: callback
});
}
var _post = function (student, callback) {
$.ajax(ApiClient.ServiceUrl, {
data: ko.mapping.toJSON(student),
type: "post",
contentType: "application/json; charset-utf-8",
statusCode: {
201 /*Created*/: callback,
400 /*BadRequest*/: function (jqxhr) {
var validationResult = $.parseJSON(jqxhr.responseText);
alert(jqxhr.responseText);
}
}
});
}
return {
get: _get,
post: _post
};
}();
$(document).ready(function() {
ApiClient.Start();
});
我的學生對象是一個非常簡單的具有Id,FirstName,LastName的C#對象。 get()函數沒有任何問題,它只是post()中的回調函數,不能推送結果數據。此外,從服務器返回的數據看起來是正確的:
{"Id":"rea","FirstName":"asdf","MiddleName":null,"LastName":"rrr"}
你可以接受你自己的答案並關閉這個問題。你沒有獲得任何聲望,但其他人不會再試圖寫出答案。 :) – bikeshedder
是的,會做。首先需要2天的等待時間。 –