0

I have three observable objects as stated below:

self.firstName = ko.observable();
self.lastName = ko.observable();
self.middleName = ko.observable();

And than I have computed observable as shown below:

ko.computed(function() {
   var myMiddleName = self.middleName();
   var Id = self.generateId(self.firstName.peek(), self.lastName.peek());
   /* Other Operation */
});

As you see in above code, I am invoking computed function when value of the middleName changes. So I have assigned it to temporary variable called myMiddleName which is actually not used anywhere. Only just to invoke.

So far everything works fine. But when I run grunt lint command it gives me an error

'myMiddleName' is assigned a value but never used. (no-unused-vars)

So how can I get rid of this error ?

Update - 1

after removing variable myMiddleName as shown, warning doesn't appear. Is this correct way ?

ko.computed(function() {
   self.middleName();
   var Id = self.generateId(self.firstName.peek(), self.lastName.peek());
   /* Other Operation */
});
ConfusedDeveloper
  • 6,389
  • 4
  • 21
  • 36
  • 1
    Why do you need a dependency on the `middleName` value if you're not using it? – user3297291 Feb 21 '18 at 12:55
  • This is just a sample. I want to call computed method only when `middleName` changes. – ConfusedDeveloper Feb 21 '18 at 12:58
  • 3
    Can you not `subscribe` to just `middleName`? I can suggest hacks to suppress the warning, but it does look like you're using a bit of an anti-pattern to get something done that should be achieved differently. It's hard to tell without seeing more of the operation. – user3297291 Feb 21 '18 at 13:00
  • I have an idea of `subscribe` in mind. But I want to see other possible solution. – ConfusedDeveloper Feb 21 '18 at 13:14

1 Answers1

2

As mentioned by @user3297291 in the comments, the right way to solve this is by using a subscriber. If you use a computed, the computed will recompute when an observable changes. If you only want this to happen when 1 observable changes, subscribers are the way to go.

I am guessing your use case is far from your example, its possible that more details about your situation could explain this far better than the existing code.

A simple example:

function ViewModel() {

  self.firstName = ko.observable();
  self.lastName = ko.observable();
  self.middleName = ko.observable();

  self.generatedId = ko.observable();

  self.middleName.subscribe(function(newValue) {
    self.generatedId(self.firstName() + " " + self.lastName());
    console.log(self.generatedId())
  });

}

ko.applyBindings(new ViewModel())
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

FirstName: <input data-bind="value: firstName" /> <br> MiddleName:
<input data-bind="value: middleName" /> <br> LastName: <input data-bind="value: lastName" /><br>
John Pavek
  • 2,595
  • 3
  • 15
  • 33