How should I be cleaning up KnockoutJS ViewModels?

后端 未结 1 1581
终归单人心
终归单人心 2021-02-05 21:33

I have a single-page app where the user pages through lists of items. Each item, in turn, has a list of items.

An observable array is updated with new items from the ser

相关标签:
1条回答
  • 2021-02-05 22:11

    The JavaScript garbage collector can only dispose a computed observable once all references to it and its dependencies are dropped. That's because observables keep a reference to any computed observables that depend on them (and vice versa).

    One solution is to make the computed observable dispose itself when it no longer has any dependencies. This can be done easily using a helper function like this.

    function autoDisposeComputed(readFunc) {
        var computed = ko.computed({
            read: readFunc,
            deferEvaluation: true,
            disposeWhen: function() {
                return !computed.getSubscriptionsCount();
            }
        });
        return computed;
    }
    
    0 讨论(0)
提交回复
热议问题