简体   繁体   中英

knockout.js guideline for ()

I'm having difficulty in understanding when I should be using () to call my variables in knockout.js.

Let's say for example:

function RandomViewModel() {
    var self = this;
    self.randomJ = new randomSquare;
}

var randomSquare = ko.observable({
    innate: ko.observableArray([ { star: "randomStar", type: "starList" } ])
});

If I wanted to set the text of a div to the element inside randomJ, this would be the code:

<div data-bind="text: randomJ.innate()[0].star"></div>

The following however do not work:

<div data-bind="text: randomJ().innate()[0].star"></div>
<div data-bind="text: randomJ.innate[0].star"></div>

I'm just wondering if anyone knows of a clear guideline as to when and how () should be used with knockout.js variable handling - both within html and javascript.

I'm currently refactoring my previous code to work with knockout and I'd like to get a firm grip of concepts before I start jumping into nested arrays of objects, etc. I'd rather not be assuming things.

Any comments on the above javascript are also much welcome.

If variable var is an observable, you get its value with var() (because observables are actually functions that return the current value). But there is a convenient exception: if the expression that you refer to in data-bind resolves to an observable, you may leave out the parantheses, as knockout.js will recognize the observable type.

Usually, for an observable that contains an object with an observable array of non-observable values, you would have to use this:

randomJ().innate()[0].star

But your example has a flaw: randomJ is actually no observable! In this line

self.randomJ = new randomSquare;

you use an observable as a constructor function. This is not intended usage and leads to the following result: you get a new object (not a function, in particular not an observable!) with the same properties as the observable. The latter is the reason that randomJ.innate is in fact the original observable array of randomSquare.

it should be:

self.randomJ = randomSquare;

or directly:

self.randomJ = ko.observable({
    innate: ko.observableArray([ { star: "randomStar", type: "starList" } ])
});

If you intended to use randomSquare as a constructor/factory for several observables, you will have to do it like so:

var randomSquare = function() {
    return ko.observable({
        innate: ko.observableArray([ { star: "randomStar", type: "starList" } ])
    });
}
self.randomJ = randomSquare();

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