所以我使用KnockoutJS与多个视图模型工作,像这样:
function firstViewModel() {
var self = this;
self.dataArray = ko.observableArray([
{ title: "title1", theData: "data1" },
{ title: "title2", theData: "data2" },
{ title: "title3", theData: "data3" },
]);
};
function secondViewModel() {
var self = this;
self.addData = function() {
firstViewModel.dataArray.push({ title: "newTitle", theData: "newData" });
// trying to trigger dataArray in firstViewModel, doesn't work
}
};
ko.applyBindings(new firstViewModel(), document.getElementById('first'));
ko.applyBindings(new secondViewModel(), document.getElementById('second'));
然后像这样:
<div id="first" data-bind="with: dataArray">
<ul data-bind="foreach: $data">
<li data-bind="text: theData"></li>
</ul>
</div>
<div id="second">
<button data-bind="click: addData">add</button>
</div>
它的结构像这样的原因是因为我有一个第三视图模型和元素重叠的DOM。我也不知道如何让它工作。
是否有任何方法来保持结构和引用firstViewModel的secondViewModel内部?firstViewModel.theData.push("newData");显然不起作用,但我认为我应该包括它,以进一步澄清我要做的事情。
我是一个全新的KO -抱歉,如果这是一个愚蠢的问题。
EDIT:看起来我明白了!
如果我从firstViewModel中删除'self',它会工作…
dataArray = ko.observableArray([
{ title: "title1", theData: "data1" },
{ title: "title2", theData: "data2" }
]);
然后self.addData = function() {
dataArray.push({ title: "newTitle", theData: "newData" });
}
我还不知道是否有删除'self'的后果,但它的工作到目前为止。
就我个人而言,我更喜欢保持我的模型去耦合,并使用发布/订阅模式来允许它们相互通信。参见我对knockoutJS变量依赖的回答
此外,如果您确实想这样做,您也可以查看knockout postbox来完成同样的事情。
您可以传递第一个视图模型的引用:
function firstViewModel() {
var self = this;
self.dataArray = ko.observableArray([
{ title: "title1", theData: "data1" },
{ title: "title2", theData: "data2" },
{ title: "title3", theData: "data3" },
]);
};
function secondViewModel(firstViewModel) {
var self = this;
self.addData = function() {
firstViewModel.dataArray.push({ title: "newTitle", theData: "newData" }); // doesn't work
}
};
var firstVm = new firstViewModel();
var secondVm = new secondViewModel(firstVm);
ko.applyBindings(firstVm, document.getElementById('first'));
ko.applyBindings(secondVm, document.getElementById('second'));