I am working on KnockoutJs and I have used valueUpdate:'afterkeydown' with textboxes and valueUpdate: 'change' with select elements to subscribe the respective changes and do SAME task. I want to call a same function via subscribe after each of their value changes.
To make it more clear, I'm onto something like below:
<input type="text" data-bind="value: val1, valueUpdate: 'afterkeydown'"/>
<input type="text" data-bind="value: val2, valueUpdate: 'afterkeydown'"/>
<select data-bind="value: sel1, valueUpdate:'change'">
<select data-bind="value: sel2, valueUpdate:'change'">
And in javascript, I've subscribed every changes like this:
viewModel.val1.subscribe(function () {
doSameWork();
});
viewModel.val2.subscribe(function () {
doSameWork();
});
viewModel.sel1.subscribe(function () {
doSameWork();
});
viewModel.sel2.subscribe(function () {
doSameWork();
});
################################
var doSameWork = function(){ alert('some work done!'); };
If I'm calling same function with every valueUpdate, then I was wondering if there is any way to subscribe every valueUpdate in a single subscribe(saving LOC) or anything like that rather than subscribing four value updates separately if I have to do same thing with each of them. Thanks in advance. :)
You can create only one event handler and "share" it to all observables
var ViewModel = function () {
var self = this;
self.onValueChanged = function (newValue) {
// your task
alert('some work done!');
};
self.val1 = ko.observable();
self.val1.subscribe(self.onValueChanged);
self.val2 = ko.observable();
self.val2.subscribe(self.onValueChanged);
self.sel1 = ko.observable();
self.sel1.subscribe(self.onValueChanged);
self.sel2 = ko.observable();
self.sel2.subscribe(self.onValueChanged);
};
See fiddle
@Accssharma :
The first time a computed is evaluated, the ko engine detects dependencies between observables and computeds. So when you write this :
ko.computed(function(){ val1(); val2(); sel1(); sel2(); doSameWork(); });
Ko registers val1, val2 sel1 and sel2 as a dependency of the computed. This means if val1 or val2.. changed the computed may change too. So when an observable (eg val1) is changed the computed needs to be evaluated. That's why the doSameWork function is called.
I hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With