简体   繁体   中英

The difference between the methods in knockoutjs

The difference between getFullName1 and getFullName2 exists?

ViewModel:

var viewModel = {
    firstName: ko.observable("Vasya"),
    lastName: ko.observable("Petrov"),
    getFullName1: function() {
        return this.firstName() + " " + this.lastName();
    }
};

viewModel.getFullName2 = ko.dependentObservable(function() {
    return this.firstName() + " " + this.lastName();
}, viewModel);

// Activates knockout.js
ko.applyBindings(viewModel);

Template

<p>Full name 1: <span data-bind="text: getFullName1()">todo</span></p>
<p>Full name 2: <span data-bind="text: getFullName2()">todo</span></p>
<p>First name: <input data-bind="value: firstName"></p>

A few things:

  • getFullName1 is not bound to your viewModel, so depending on where it is called, the value of this may not be your viewModel. This is particularly important in Knockout, where your code is being called indirectly and references to functions are passed around. This may not affect you, but especially comes into play when dealing with collections/templates.

  • bindings are implemented using dependentObservables, so in the way that you are using it, they will both update their spans when firstName or lastName changes..

  • Since, getFullName2 is a dependentObservable it will update itself anytime one of its dependencies changes. It does not matter if it is bound to anything. It also has other features available to you like creating manual subscriptions against it.

  • You can also just say test: getFullName2 with a dependentObservable, as it will get unwrapped.

  • The most important reason though is that dependentObservables are only updated when their dependencies change and their actual value is cached inside of it. So, if I called getFullName1 100 times, it would do the work all 100 times. If I called, getFullName2 100 times, it would simply return the latest value that it calculated on creation or when a dependency last changed.

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