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:


<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 };

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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.