Xepe
Xepe

Reputation: 235

How can I do the following validation using knockout js?

How can I do the following validation using knockout js? I have the following view model:

function ViewModel () {
        var self = this;
        self.ListName = ko.observable();
        self.Current = ko.observable();
        self.MyVideos = ko.observableArray();
    }

Where MyVideos have the following structure:

    [{
                "VideoID": 1,
                "VideoName": "First Video"
    },
    {
                "VideoID": 2,
                "VideoName": "First Video"
    }]

So Current and VideoId are the relation, and I want to render the VideoName with the self.Current value.

Upvotes: 0

Views: 138

Answers (2)

RP Niemeyer
RP Niemeyer

Reputation: 114792

It sounds like Current is the VideoId and you want to display the VideoName. For that scenario you could do:

self.CurrentName = ko.computed(function() {
    var currentId = self.Current();

    var currentVideo = ko.utils.arrayFirst(self.MyVideos(), function(video) {
        return currentId === video.VideoId; 
    });

    return currentVideo ? currentVideo.VideoName : 'none';

});

Upvotes: 1

John Papa
John Papa

Reputation: 22298

You can loosely using this quickly written code. It create a computed to find the first array item and its VideoName property. Of course, add error checking, too.

self.Current = ko.computed(function(){
    return self.MyVideos()[0].VideoName;
});

Upvotes: 1

Related Questions