当我运行我的应用程序时,我收到以下错误“SCRIPT5007:无法获取未定义或空引用的属性'Id'。”知道是什么导致此代码在File:app.js,Line:51,Column:9中断?
以下是app.js文件中的完整代码。
var ViewModel = function () {
var self = this;
self.books = ko.observableArray();
self.error = ko.observable();
self.detail = ko.observable();
self.authors = ko.observableArray();
self.newBook = {
Author: ko.observable(),
Genre: ko.observable(),
Price: ko.observable(),
Title: ko.observable(),
Year: ko.observable()
}
var booksUri = '/api/books/';
var authorsUri = '/api/authors/';
function ajaxHelper(uri, method, data) {
self.error(''); // Clear error message
return $.ajax({
type: method,
url: uri,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
}).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
function getAllBooks() {
ajaxHelper(booksUri, 'GET').done(function (data) {
self.books(data);
});
}
self.getBookDetail = function (item) {
ajaxHelper(booksUri + item.Id, 'GET').done(function (data) {
self.detail(data);
});
}
function getAuthors() {
ajaxHelper(authorsUri, 'GET').done(function (data) {
self.authors(data);
});
}
self.addBook = function (formElement) {
var book = {
AuthorId: self.newBook.Author().Id,
Genre: self.newBook.Genre(),
Price: self.newBook.Price(),
Title: self.newBook.Title(),
Year: self.newBook.Year()
};
ajaxHelper(booksUri, 'POST', book).done(function (item) {
self.books.push(item);
});
}
// Fetch the initial data.
getAllBooks();
getAuthors();
};
ko.applyBindings(new ViewModel());
答案 0 :(得分:1)
处理null作者案例非常简单。
self.addBook = function (formElement) {
var author = self.newBook.Author() || {},
book = {
AuthorId: author.Id,
Genre: self.newBook.Genre(),
Price: self.newBook.Price(),
Title: self.newBook.Title(),
Year: self.newBook.Year()
};
//Is authorId required??
if (!book.AuthorId) {
throw new Error('Author ID required!');
}
...
}