我正在寻找解决我的问题的方法。我需要在可观察数组的内容中绑定某个元素的类。我有一个可观察的数组,里面是一个可观察的列表,我需要绑定到符合我的条件的observable
function ViewModel(Name) {
var self = this;
self.Observable1 = ko.observableArray([]);
self.Observable1.push(new myfunction2(name));
self.Observable1.push(new myfunction2(name + "1"));
}
function myfunction2(Name) {
var self = this;
self.Name = ko.observable(Name);
self.Name2 = ko.observable(Name);
}
ko.applyBindings(new ViewModel("Hello"));
根据我的代码,我有一个包含一个可观察数组的视图模型,在该可观察数组中,它有另一个observable我需要将我的元素绑定到那个,如果它符合我的条件我将如何做到这一点?
这是元素
<div data-bind="???????????????" ></div>
示例条件我想绑定到数据Name2,如果Name =&#34; Hello&#34;
的值答案 0 :(得分:3)
如果我理解你的问题,你可以为你的ViewModel类创建一个计算属性,如下所示:
self.SelectedObject = ko.computed(function () {
return ko.utils.arrayFirst(self.Observable1(), function (element) {
return element.Name() === "whatever";
});
});
然后,在Html中:
<div data-bind="with: SelectedObject">
<span data-bind="text: Name2"></span>
</div>
To&#34;吃掉我自己的垃圾&#34;,这是一个基于你的代码的工作示例。
function ViewModel(name) {
var self = this;
self.Observable1 = ko.observableArray([]);
self.Observable1.push(new myfunction2(name));
self.Observable1.push(new myfunction2(name + "1"));
self.SelectedObject = ko.computed(function () {
return ko.utils.arrayFirst(self.Observable1(), function (element) {
// Try replacing this with "Hello1", and it will select the other element in the array
return element.Name() === "Hello";
});
});
}
function myfunction2(Name) {
var self = this;
self.Name = ko.observable(Name);
self.Name2 = ko.observable(Name);
}
ko.applyBindings(new ViewModel("Hello"));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<body>
<div data-bind="with: SelectedObject">
<span data-bind="text: Name"></span>
</div>
</body>
&#13;