Many times while working with MV* pattern in JavaScript, we need to extend the basic structure of observables. Quite often we are willing to know when the value of a DOM element, bind with an observable, has changed it’s value. In this post, we will see how we can get the value changed event of an observable by extending the observable.
First of all, let’s create our view. We would have an input text box (where user would enter the value) and a span (where we would print the message). Here’s the UI:
1: <input type="text" data-bind='value: username'/><br /> <br />
2: <span data-bind='visible: username.showMessage, text: username.Message'></span>
Next comes the JavaScript part. Well, we would use the same old ViewModel technique.
1: function AppViewModel() {
2: this.username= ko.observable().extend({ PropertyChanged: this });
3: }
4:
5: ko.applyBindings(new AppViewModel());
Here is the important thing.
Let’s now create the method “PropertyChanged”, which is basically an extender method.
1: ko.extenders.PropertyChanged= function(el) {
2:
3: //add some sub-observables to our observable
4: el.showMessage= ko.observable();
5: el.Message= ko.observable();
6:
7: //define a function to do validation
8: function validate(valueOfEl) {
9: el.showMessage(true);
10: if(valueOfEl == "Neelesh"){
11: el.Message("You are awesome!!!");
12: }else if(valueOfEl != undefined || valueOfEl != null ){
13: el.Message("You are awful!!!");
14: }
15: }
16:
17: //initial validation
18: validate(el());
19:
20: //validate whenever the value changes
21: el.subscribe(validate);
22:
23: //return the original observable
24: return el;
25: };
The sub-observables that we have created and assigned values to, would be bind to the span in which we are supposed to show the message.
Line #21 is the most important part of the entire code. It is the soul behind subscribing the value change of the observable in target to the method validate.
In the end, we return the targeted observable by manipulating its prototype properties, like showMessage and Message, which are in turn bind with the span which is going to show the message we’ve set in the Validate method.
This is how we can extend observables in knockout. Hope you’d like the post.
0 comments