javascript - checking if inputs are set in Knockout.js -


i'm using knockout.js , want check if 2 two text inputs have value set. if are, something.

the following works, want know if there's "knockout" way using custom bindings or other way. want learn more knockout able leverage features in future more complex situations.

function datesviewmodel(startdate,enddate){      var self = this;     self.startdate = ko.observable("");     self.enddate = ko.observable("");       self.startdate.subscribe(function(newvalue) {          check_dates();     });      self.enddate.subscribe(function(newvalue) {         check_dates();     });      function check_dates(){         if(self.startdate() !== "" && self.enddate() !== ""){             alert('values set');         }     }  } 

i tried doctormick sugggest using computed function, either i'm misunderstanding use of it, or it's not working.

self.datesentered = ko.computed(function() {     if(self.startdate() !== "" && self.enddate() !== ""){         return self.startdate() && self.enddate();     } });   self.datesentered.subscribe(function() {    alert(self.datesentered); }); 

the alert triggered every time either of dates changed. also, it's returning bunch of code.

it depend on you're trying achieve i'd use computed based on snippet above, so...

self.datesentered = ko.computed(function() {     return self.startdate() && self.enddate(); });  self.datesentered.subscribe(function(value) {    if(value) {        alert("hurrah, both values entered");    } }); 

that way can bind or subscribe datesentered , whatever once both have been keyed in. can see, simplifies original code quite significantly.


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -