如何访问绑定到挖空中不同元素的视图模型?



我有一个组件需要访问不同组件的模型并设置标志的情况。

所以,类似于这样:

<div id='component1'>
<div data-bind='visible: showMe()'>Shown</div>
</div>
<div id='component2'>
<button data-bind='click: setFlag()'>Set the flag</button>
</div>

Javascript:

(function () {
var vm1 = {
showMe: ko.observable(false)
};
ko.applyBindings(vm1, $("#component1"));
})();
(function () {
var vm2 = {
setFlag: function () {
// How to set showMe to true in vm1                
}
}
ko.applyBindings(vm2, $("#component2"));
})();

根据您的代码,我认为#component1是一个部分类似视图的东西,这取决于#component2。 但由于它没有直接嵌入#component1因此必须有一些共同的容器来容纳它们。这个公共容器应被视为两个组件的主机。

通常,您应该始终将UI的逻辑上相互关联的部分包装在一个公共容器中,并为该容器定义一个视图模型,该视图模型不执行任何其他操作,而是保存各个部件或组件的视图模型,无论您喜欢什么,也许还有一些协调逻辑,例如定义可见的内容和时间,就像您的问题一样。

所以我会像下面这样做:

function component1ViewModel() {
};
function component2ViewModel() {
};
function mainViewModel() {
var self = this;        
// Doesn't have to be observable if the value is never changed        
this.component1VM = ko.observable(new component1ViewModel());
this.component2VM = ko.observable(new component2ViewModel());
this.component1Visible = ko.observable(false);
this.setComponent1Visible = function(visible) {
self.component1Visible(visible);
};
};

然后在您的标记中:

<div id="main">
<div id="component1" data-bind="with: component1VM, visible: $parent.component1Visible()">
Yay I'm visible!
</div>
<div id="component2" data-bind="with: component2VM">
<button type="button" data-bind="click: $parent.setComponent1Visible.bind($data, true)">
Show component 1
</button>
</div>
</div>

最后,初始化:

$(function() {
ko.applyBindings(new mainViewModel(), $('#main')[0]);
});

总而言之,通过将两个相互依赖的视图模型包装在一个公共容器中,您可以使用元素 KNOCKOUT 在标记中为您提供$parent,并且使用该引用,您可以在视图模型层次结构中的上层对象中调用函数。

但是,我想指出的是,使用这种方法,如果您愿意,可以通过添加正确的导航直接调用component1$parent.component1.someFunction.bind($data, val1, val2).所以其实你不仅限于定义共同父级中与可见性相关的东西,你可以使用任何你更喜欢的方法,发现更具可读性。

最新更新