简体   繁体   English

如何绑定到可观察数组内部的某个可观察对象

[英]how to bind to a certain observable inside the observable array

hi im currently looking for a solution for my problem the thing is. 您好,即时通讯目前正在寻找解决我问题的方法。 i need to bind a class of a certain element in the content of an observable array. 我需要在可观察数组的内容中绑定某个元素的类。 i have an observable array and inside that is a list of observables i need to bind to that observable that meets my condition 我有一个可观察的数组,里面是可观察对象的列表,我需要绑定到符合我条件的可观察对象

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"));

based on my code i have a view model that contains an observable array and inside that observable array it has another observable i need to bind my element to that if it meets my condition how am i going to do that? 根据我的代码,我有一个包含可观察数组的视图模型,并且在该可观察数组内部有另一个可观察数组,如果需要,我需要将我的元素绑定到该元素上,我该怎么做?

this is the Element 这是元素

<div data-bind="???????????????" ></div>

example condition i want to bind to the data Name2 if the value of Name = "Hello" 示例条件如果Name的值=“ Hello”,我想绑定到数据Name2

If I understand your question right, you could make a computed property to your ViewModel class, like so: 如果我正确理解您的问题,则可以为ViewModel类添加计算属性,如下所示:

self.SelectedObject = ko.computed(function () {
    return ko.utils.arrayFirst(self.Observable1(), function (element) {
        return element.Name() === "whatever";
    });
});

Then, in Html: 然后,在HTML中:

<div data-bind="with: SelectedObject">
    <span data-bind="text: Name2"></span>
</div>

To "eat my own garbage", here's a working example, based on your code. 为了“吃我自己的垃圾”,这是一个基于您的代码的工作示例。

 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")); 
 <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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM