我的數據模型由兩個對象組成;項目和任務。 我通過JSON和MVC服務加載從DB我的數據和地圖我observableArrays這樣的:如何訪問來自不同對象範圍的挖空觀測數據
viewModel = function() {
var self = this;
// some code...
// projects
self.Projects = ko.observableArray();
var mappedProjects = [];
$.ajax({
url: "myService/GetProjectsByUserId",
data: "userID=" + meID,
dataType: 'json',
async: false,
success: function (allData) {
mappedProjects = $.map(allData, function (item) {
return new Project(item);
});
}
});
self.Projects(mappedProjects);
// tasks
self.Tasks = ko.observableArray();
var mappedTasks = [];
$.ajax({
url: "myService/GetTasksByUserID",
data: "userid=" + meID,
dataType: 'json',
async: false,
success: function (allData) {
mappedTasks = $.map(allData, function (item) {
return new Task(item, self.Projects); // is there a smarter way to access self.Projects from the Scene prototype?
//return new Task(item);
});
}
});
self.Tasks(mappedTasks);
//some more code...
};
其中
Project = function (data) {
this.projectID = data.projectID;
this.type = ko.observable(data.type);
};
Task = function (data, projects) {
this.taskID = data.taskID;
this.projectID = data.projectID;
//this.projecttype = ??? simpler solution?
this.projecttype = ko.computed(function() { // Is there a simpler way to access 'viewModel.Projects' from within 'Task'?
var project = ko.utils.arrayFirst(projects, function (p) {
return p.projectID === self.projectID;
});
if (!project) {
return null;
}
else {
return project.headerType();
}
});
};
的事情是(你看),我要訪問的項目類型在Task對象內部。有沒有比使用self.Projects作爲輸入實例化對象更簡單的方法?
可以self.Projects被綁定時,以某種方式定義,所以我可以通過DOM訪問它?
yes!如果你在'viewModel'函數中聲明瞭所有的函數,那麼'self.Projects'就可以在全局上用於內部函數,即Task。 –
我看到的稍微大一點的問題是,你正在初始化ajax調用後的self.projects;因爲它是異步的,self.Projects永遠不會使用實際的映射數據來設置,而是空的數組 – dfperry
如何從Task = function(data){}訪問viewModel? 當我訪問數據時viewModel沒有被綁定,會不會導致問題? –