1
\$\begingroup\$

I am trying out for the first time knockoutjs and babeljs and have a question on how to do computed observables properly. Both fullName and fullNameComp properties are updated whenever firstName and lastName changes so not sure about pros/cons:

<h2>employee</h2>
<input type="text" data-bind="value: firstName, valueUpdate: 'keyup'" />
<input type="text" data-bind="value: lastName, valueUpdate: 'keyup'" />
<p>Full name getter: <spane data-bind='text: fullName'></span></p>
<p>Full name pure computed: <span data-bind='text: fullNameComp'></span></p>

import ko from 'knockout';
import templateMarkup from 'text!./employee.html';
class Employee {
constructor(params) {
 this.firstName = ko.observable('John');
 this.lastName = ko.observable('Smith');
 this.fullNameComp = ko.pureComputed(function() {
 return this.firstName() + " " + this.lastName();
 }, this);
}
get fullName() {
 return this.firstName() + ' ' + this.lastName();
}
dispose() {
 // This runs when the component is torn down. Put here any logic necessary to clean up,
 // for example cancelling setTimeouts or disposing Knockout subscriptions/computeds.
}
}
export default { viewModel: Employee, template: templateMarkup };
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 25, 2015 at 17:30
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Your fullName() function will return the same result but only when called. The computed will always have the updated value and can be used as a trigger for other code if needed. For example, you can subscribe to fullNameComp but you cannot subscribe to fullName as it doesn't extend from KO's observable.

If the function fullName meets your needs then use it.

janos
113k15 gold badges154 silver badges396 bronze badges
answered Feb 16, 2016 at 16:04
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.