How to add new computed property in knockoutjs object at run time?

384 Views Asked by At

I have program like below in knockout js

<input type="text" data-bind="value:firstName" />
<input type="text" data-bind="value:lastName" />
<p data-bind="text:fullName"></p>
    <script type="text/javascript" language="javascript">
        // Here's my data model
        var Person = function (id, first, last) {
            this.id = ko.observable(id);
            this.firstName = ko.observable(first);
            this.lastName = ko.observable(last);


        };

        Person.prototype.fullName = ko.computed(function () {
            return this.firstName() + " " + this.lastName();
        }, Person);


        ko.applyBindings(new Person(1, "kapil", "Garg"));
    </script>

I am getting error that this.firstName() is not a function. how can i add new computer property like that?

2

There are 2 best solutions below

0
On

use

 <input type="text" data-bind="value:firstName()" />


  <input type="text" data-bind="value:lastName()" />

You missed the paranthesis, that is why knockout is complaining.

1
On

You missed the 'new' keyword when instantiating your ViewModel