How can I use knockout's $parent/$root pseudovariables from inside a .computed() observable?

前端 未结 2 1118
予麋鹿
予麋鹿 2020-12-13 08:17

Inside a knockout.js binding expression, I can use the $data, $parent, and $root pseudovariables. How can I get the equivalent of those pseudovariables when I\'m using a ko.

2条回答
  •  北海茫月
    2020-12-13 09:04

    In my experience the approach in @RP Niemeyer's answer is fine if Items live for the duration of the application. But if not, it can lead to memory leaks, because Item's computed observable sets up a reverse dependency from the ViewModel. Again, that's ok if you never get rid of any Item objects. But if you do try to get rid of Items they won't get garbage collected because knockout will still have that reverse dependency reference.

    You could make sure to dispose() of the computed, maybe in a cleanup() method on Item that gets called when the item goes away, but you have to remember to do that whenever removing Items.

    Instead, why not make Item a little less smart and have ViewModel tell it when it is selected? Just make Item's isSelected() a regular old observable and then in ViewModel subscribe to selectedItem and update inside that subscription.

    Or, use @RP Niemeyer's pub/sub solution. (To be fair, this solution came about after his answer here.) You'll still need to clean up, though, because it creates reverse dependencies, too. But at least there's less coupling.

    See the answer to my recent question on this same topic for more details.

提交回复
热议问题