Don
Don

Reputation: 131

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"

Upvotes: 0

Views: 417

Answers (1)

Steen T&#248;ttrup
Steen T&#248;ttrup

Reputation: 3835

If I understand your question right, you could make a computed property to your ViewModel class, like so:

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

Then, in 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>

Upvotes: 3

Related Questions