gpt4 book ai didi

javascript - knockout.js 从另一个 View 模型初始化 View 模型

转载 作者:行者123 更新时间:2023-11-30 15:24:38 25 4
gpt4 key购买 nike

这是我的代码

View 模型 1

function AppViewModel() {
var self = this;
self.boardtext = ko.observable();
self.board = ko.observableArray([
{ boardname: 'Board' },
{ boardname: 'Board' },
{ boardname: 'Board' }
]);

self.addboard = function () {
self.board.push({ boardname: self.boardtext() });
// initialize ListModal to zero
};

self.removeboard = function () {
self.board.remove(this);
}

View 模型 2

 var initialData = []; 

var ListModal = function (lists) {
var self = this;
self.cardtext = ko.observable();
self.lists = ko.observableArray(ko.utils.arrayMap(lists, function (list) {
return { listname: list.listname, cardlists: ko.observableArray(list.cardlists), showRenderTimes: ko.observable(false) };
}));



};

ko.applyBindings(new AppViewModel(), document.getElementById("container1"));
ko.applyBindings(new ListModal(initialData), document.getElementById("container2"));

一旦我按下 addboard,如何将我的 ListModal 设置为零?

最佳答案

如果您想重新初始化 listModal,请尝试将这 2 个 View 模型包装在 1 个 View 模型中,以便它们可以相互关联。然后您可以执行以下操作:

var initialData = []; 

var ListModal = function (lists) {
var self = this;
self.cardtext = ko.observable();
self.lists = ko.observableArray(ko.utils.arrayMap(lists, function (list) {
return { listname: list.listname, cardlists: ko.observableArray(list.cardlists), showRenderTimes: ko.observable(false) };
}));
}

function AppViewModel(parent) {
var self = this;

// this will keep the object of ViewModel
self.parentObject = parent;

self.boardtext = ko.observable();
self.board = ko.observableArray([
{ boardname: 'Board' },
{ boardname: 'Board' },
{ boardname: 'Board' }
]);

self.addboard = function () {
self.board.push({ boardname: self.boardtext() });

// re-initialize listModal
self.parentObject.listModal(new ListModal(initialData));
};

self.removeboard = function () {
self.board.remove(this);
};
}

function ViewModel() {
var self = this;
self.appViewModel = ko.observable(new AppViewModel(self));
self.listModal = ko.observable(new ListModal(initialData));
}

// provide another div which wrap container 1 and 2 together
ko.applyBindings(new ViewModel(), document.getElementById("container1And2"));

关于javascript - knockout.js 从另一个 View 模型初始化 View 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43182597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com