user1147971
user1147971

Reputation: 55

Knockout JS subscribe method issue

We are using KnockoutJS for handling UI and moving parts in UI.

So here is the problem:

We have grid on which we have filter columns. It filters data on tab-out. Recently we received a request to Filter data on Enter. Since knockout provide subscribe method that automatically triggers action i want. Is there a way to have custom implementation of subscribe method which can be triggered on enter.

var triggerQueryIfOk = function () {
    if (!self.isLoading() && !self.isOpening) self.runQuery();
};
self.filters.empName.subscribe(triggerQueryIfOk);
 };

self.getQueryParameters = function () {

    return {
       empName: self.filters.empName()                  };
};

self.runQuery = function () {

    if (!self.isLoading()) {

        self.isLoading(true);

        // prepare query data
        var query = self.getQueryParameters();

        // hit server
        $.ajax({
            url: self.getEmployeesUrl,
            type: "POST",
            data: JSON.stringify(query),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (rawInvestmentsData) {
                processEmployees(rawInvestmentsData);
                self.isLoading(false);
            },
            error: function () {
                self.isLoading(false);
            }
        });
    }

};

Upvotes: 1

Views: 1580

Answers (2)

Judah Gabriel Himango
Judah Gabriel Himango

Reputation: 60011

What is the filter column - an HTML text box?

If so, you can push values from your text box into the observable using the valueUpdate binding option:

<p>Your value: <input data-bind="value: someValue, valueUpdate: 'afterkeydown'" /></p>

The ko.observable called "someValue" will be pushed new values after every key down.

Alternately, you can bind the key down event and look for enter key:

<p>Your value: <input data-bind="value: someValue, event: { keydown: onKeyDown }" /></p>

...

viewModel.onKeyDown = function (sender, e) {
    if (e.keyCode === 13) { 
       // the enter key, do something here... 
    }
}

Upvotes: 1

maxfridbe
maxfridbe

Reputation: 5970

Judah's answer is close except the onkeydown method should look like this(at least for me it did):

self.OnSearchTermKeydown = function (me,event){
            if (event.keyCode === 13) { 
              location.href=searchURL + me.SearchValue;
              return false;
            }

              return true;
          };

Upvotes: 1

Related Questions