Knockout.js 的 viewModel 上的一对多关系

问题描述 投票:0回答:1

我是KO新手。我尝试使用 knockout.js 设计一个简单的应用程序,但我不知道如何设计 modelViews 和模型。

我尝试在单击功能行时加载任务。但是加载一次后,我想从内存中显示它,而不是从数据库中显示。例如,当单击所有功能时,当前会话将不会有数据库查询。

在 KO 上,我不知道将我的 observableArrays(任务、注释)放在哪里。

它们应该是模型或视图模型的属性吗?

这是我的应用程序结构。 功能有很多任务,任务有很多注释。

用户界面就像...

查看模型:

var taskViewModel = {
     notes: ko.observableArray(),

     addNote: function (newNote) {
         this.notes.push(newNote);
  }
} 

var featureViewModel = {
    tasks: ko.observableArray(),

    addTask: function(newTask){
             this.tasks.push(newTask);
},

taskClicked: function (selectedTask) {
        GetNotes(selectedTask.TaskId);
         }
}

var projectViewModel = new projectViewModelFunc();
function projectViewModelFunc() {
    var self = this;
    self.features = ko.observableArray();

    self.addFeature = function (newFeature) {
         this.features.push(newFeature);
       };
}

ko.applyBindings(taskViewModel, $('#notes')[0]);
ko.applyBindings(featureViewModel, $('#tasksPanel')[0]);
ko.applyBindings(projectViewModel, $('#features')[0]);

型号:

function noteModel(data) {
   this.UserCreatedFullName= data.UserCreated.FullName;
   this.CreatedDate = data.CreatedDate;
   this.NoteId = data.NoteId;
   this.Content = data.Content;
   this.TaskId = data.TaskId;

   this.TaskHeader = function () { return this.UserCreatedFullName + " (" + this.CreatedDate + ") : "; };
}

function taskModel(data) {
    this.TaskId = data.TaskId;
    this.Title = data.Name;
    this.Status = data.Status.Name;
    this.CreatedDate = data.CreatedDate;
    this.UserCreatedFullName = data.UserCreated.FullName;
}

function featureModel(data, selected) {
    var self = this;
    self.FeatureId = data.FeatureId;
    self.Name = data.Name;
    self.Status = data.Status.Name;
    self.CreatedDate = data.CreatedDate;
    self.UserCreatedFullName = data.UserCreated.FullName;

    this.IsSelected = ko.computed(function () {
        return selected() === self;
    });
}

数据库上下文函数(只是为了更清楚)

function GetNotes(taskId) {
    var url = "/Note/GetNotes";
    taskViewModel.resetNotes();
    $.get(url, { "TaskId": taskId }, function (data) {
        $.each(JSON.parse(data), function (i, item) {
            taskViewModel.addNote(new noteModel(item));
        });
    });
};

function GetFeatures() {
    var url = "/Project/GetFeatures";
    taskViewModel.resetNotes();
    $.get(url, "", function (data) {
        $.each(JSON.parse(data), function (i, item) {
            projectViewModel.addFeature(new featureModel(item, projectViewModel.selectedFeature));
        });
    });
};

function GetTasks(FeatureId) {
    var url = "/Task/GetTaskList";
    $.get(url, { "FeatureId": FeatureId }, function (data) {

        $.each(JSON.parse(data), function (i, item) {
            featureViewModel.addTask(new taskModel(item));
        });
    });
};
knockout.js relationship viewmodel one-to-many
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.