Recently I bumped on rather weird code in the project I'm currently working on. Here is the isolated example depicting the issue:
<html lang="en-US">
<head>
<meta charset="UTF-8">
</head>
<body>
<input type="text" data-bind = "value: firstName">
<input type="text" data-bind = "value: lastName">
<br /> <br />
<span data-bind = "text: firstName"></span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script>
var myViewModelProto = function(){
self = this;
this.firstName = ko.observable("John");
this.lastName = ko.observable("Smith");
ko.computed(function(){
alert(self.lastName());
});
};
var vm = new myViewModelProto();
ko.applyBindings(vm);
</script>
</body>
</html>
The alert in anonymous computed observable will fire not only when viewModel is created, but also each time a dependent observable (lastName in this case) is changed after constructor function is complete. In the code I'm maintaining right now this is used to run specific code to redraw bound ui widgets. So my questions are:
- Is this a bug in knockout which eventually be fixed? (So I'd better remove this magic whatsoever, before it will stop working after update)
- Is this a common pattern of sorts and perfectly fine to use?
UPDATE: In the real case I encountered in the project I need to maintain there are several lines of code in place of alert with no direct references to a dependent observable, value of observable is changed in some nested function calls made from within computed. The example given is extremely simplified. Also, both computed observables are decorated with throttle extender which is probably was sole purpose of making them computed in first place.
computed
in the first place? – haim770