How to get an observableArray's length?

前端 未结 3 1141
后悔当初
后悔当初 2020-12-17 07:42

I am attempting to create an array of contract line items (CLINs) that will be displayed as individual div elements below a header of general contract informati

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 07:59

    TL;DR / Quick Fix

    Execute the observableArray as a function to get the underlying array, then get its length:

    
    myObsArray's length is: 
    

    Why does this happen?

    Let me provide an answer that provides some details in addition to @kendaleiv's solution, and that also answers a highly related question I feel many people have:

    Why does myObsArray.length always return 0 (zero)?

    A typical repro of such a scenario would be this:

    ko.applyBindings({ myObsArray: ko.observableArray(["one", "two", "three"]) });
    
    myObsArray.length = 

    The snippet says "length = 0", instead of "length = 3".

    The key thing to note here: ko.observableArray is a function... that returns a function.

    That's right: if you assign the result of it to a variable or member, such as myObsArray in the example, that variable will be a reference to a function. So if you're asking for

    myObsArray.length
    

    then you're actually asking for the Function.length property: the number of arguments that function takes. For a function returned from ko.observableArray this will be 0 (zero).

    How do we fix this?

    The fix given in other answers is fine, let me reiterate here with this answer's example. To get the length of "the array being observed", you need to invoke said function to get the array, and then get its length:

    ko.applyBindings({ myObsArray: ko.observableArray(["one", "two", "three"]) });
    
    myObsArray.length = 


    Finally, as a footnote, OP's code is something equivalent to:

    myObsArray.length()
    

    This will find aforementioned Function.length property and try to execute it as a function (which it isn't), and will not return 0 but instead crash. Beware to not invoke length as a function, but the observable. Always invoke length as a member variable.

    Will / Can / Could this be changed?

    Very early on KO's developers considered this issue; as early as Github issue no 4. That issue explains the things I've tried to cover above too, and also shows that in the end there wasn't much that could be done to change it.

提交回复
热议问题