Knockout.js - understanding foreach and with

I studied learn.knockout.js tutorials and experimented. Can someone explain why this works [Tutorial: single page applications, step 2] (using with: chosenFolderData and foreach: mails ):

 <!-- Mails grid --> <table class="mails" data-bind="with: chosenFolderData"> <thead><tr><th>From</th><th>To</th><th>Subject</th><th>Date</th></tr></thead> <tbody data-bind="foreach: mails"> <tr> <td data-bind="text: from"></td> <td data-bind="text: to"></td> <td data-bind="text: subject"></td> <td data-bind="text: date"></td> </tr> </tbody> </table> 

but not this (using only foreach: chosenFolderData.mails ):

 <!-- Mails grid --> <table class="mails"> <thead><tr><th>From</th><th>To</th><th>Subject</th><th>Date</th></tr></thead> <tbody data-bind="foreach: chosenFolderData.mails"> <tr> <td data-bind="text: from"></td> <td data-bind="text: to"></td> <td data-bind="text: subject"></td> <td data-bind="text: date"></td> </tr> </tbody> </table> 

I suspect that since chosenFolderData is chosenFolderData observed, chosenFolderData.mails not. Can anyone tell me for sure?

Thank you very much!

- Ralph

+3
javascript
Mar 28 2018-12-12T00:
source share
1 answer

Because you are not actually getting access to the property you want with the way it is written. In the model, chosenFolderData is observable and must be called as a method to retrieve the value. To provide functionality without using with (and I suggest not using with , where high performance is needed due to overhead) ...

 <tbody data-bind="foreach: chosenFolderData().mails"> 
+6
Mar 28 2018-12-12T00:
source share
— -



All Articles