Dukakus17
Dukakus17

Reputation: 1249

Calling jquery function inside a knockout viewModel declaration. (mainly a syntax issue)

I have a viewModel called "applications" that contains information of applicants. It looks like this in a knockout-view:

[![enter image description here][1]][1]

And I tried to loop through this viewModel and filter out only one element based on a specific condition.

What I am eventually trying to do is, I want to display only one "application" element in a modal.

So, what I have done so far is,

<a href="#" data-toggle="modal" data-target="#previewApplicantModal" data-bind="attr: { 'data-applicationKey': application.applicationKey }">
    Preview Application
</a>

I added an attribute called applicationKey, so it directly retrieves the "applicationKey" of the applicant.

And I made a jquery function that returns this applicationKey by doing this:

                $('#previewApplicantModal').on('show.bs.modal', function (e) {
                    var key = $(e.relatedTarget).data('applicationkey');
                    return key;
                });

It reads the "data-applicationKey" and returns the corresponding applicationKey.

For example,

<a href="#" data-toggle="modal" data-target="#previewApplicantModal" data-bind="attr: { 'data-applicationKey': application.applicationKey }" data-applicationkey="abd263zqe">
    Preview Application
</a>

returns

abd263zqe

After that, I tried to make a new viewModel called "previewApplication" that only returns the application element that has that "applicationKey". What I did was, I looped through the "applications" viewModel and return only if the "i.application.applicationKey" is equal to the "applicationKey" returned by the jquery function that I wrote above. The code looks like this :

            self.previewApplications = ko.computed(function () {
                return ko.utils.arrayMap(self.applications(), function (i) {
                    if(i.application.applicationKey == THE JQUERY FUNCTION THAT RETURNS THE applicationKey)    
                       return i.application;
                });
            });

So, I want to return the "application" element that has the same applicationKey as the one that is returned by the jquery function, but I have no idea how to put that in syntax.

Upvotes: 0

Views: 386

Answers (1)

Jason Spake
Jason Spake

Reputation: 4304

Try modifying your jQuery event to store the key in your previewApplicationKey observable

$('#previewApplicantModal').on('show.bs.modal', function (e) {
    var key = $(e.relatedTarget).data('applicationkey');
    viewModel.previewApplicationKey(key);
});

and then in your comparison function check against that value

self.previewApplications = ko.computed(function () {
    return ko.utils.arrayMap(self.applications(), function (i) {
        if(i.application.applicationKey == self.previewApplicationKey())    
            return i.application;
    });
});

Upvotes: 1

Related Questions