سؤال

I was trying to implement the following behavior with knockout: when a user submit his login and password and it is wrong - show him the error message. When the user changes any of the inputs - hide the message.

I tried it with computed observable and understood that this is not the right approach, and after reading documentation I found about subscribing. So everything works nicely when I subscribe each input. The problem is that I am subscribing both observables to the same event (thus duplicating the code). I know that I can put duplicating code into a function and subscribe each observable to the function, but this also doesn't look so nice to me.

Enough this empty talk, here is my fiddle (click on make it wrong and then type something in input)and here is how I am doing this:

this.loginText.subscribe(function () {
   self.isError(false);
});

this.passwordText.subscribe(function () {
   self.isError(false);
});

I tried to read similar question here, but was not able to understand how exactly I can subscribe multiple observables to the same event.

هل كانت مفيدة؟

المحلول

You should use computed observable. Computed observable are calculated every time, when dependent observable changed. Thus, you can simply list all observable (which binded to your inputs) in your computed observable, and changing at least one of them call computed function.

function User() {
    var self = this;
        self.loginText      = ko.observable(null);
        self.passwordText   = ko.observable(null);
        self.isError        = ko.observable(false);

        self.makeWrong = function(){
            self.isError(true);
        }

        ko.computed(function() {
            self.loginText();
            self.passwordText();
            self.isError(false);
        });
    }

Demo

نصائح أخرى

If you don't want to use ko.computed then you can use extender. for more info about extenders http://knockoutjs.com/documentation/extenders.html

so for the same functionality extender will be

ko.extenders.ErrorCheck = function(target, option) {
  target.subscribe(function(newValue) {
    console.log("new Value is " + newValue);
    self.isError(false);
  });
  return target;
}; 

And observable will be:-

this.loginText = ko.observable(null).extend({ErrorCheck:""});
this.passwordText = ko.observable(null).extend({ErrorCheck:""});

Fiddle Demo

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top