简体   繁体   中英

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

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?

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.

实例化ViewModel时,您错过了'new'关键字

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM