Knockout component resource cleanup and memory management

Source: Internet
Author: User

Resource cleanup and memory management

Optionally, your ViewModel class can have a Dispose function, and if implemented, knockout will call this function whenever the component is destroyed (for example, because the item of the response is removed from the foreach, or if the bind becomes false)

You must use Dispose to remove any resources that are not collected by the garbage inside. For example:

    • The setinterval callback will continue to trigger until it is clearly cleared
      • Use Clearinterval (handle) to stop them, otherwise your view model may reside in memory
    • The Ko.computed property continues to receive notifications from their dependent objects until the north is clearly destroyed
      • If a dependency is about an external object, then be sure to use the computed property. Dispose (), otherwise it (or possibly your view model) will reside in memory, optionally, consider using pure computed to avoid the need for manual cleanup
    • Subscription observable continues to trigger until it is clearly destroyed
      • If you subscribe to an external observable, be sure to use subscription. Dispose (), otherwise the callback (and possibly your view model) will reside in memory)
    • Create an event handle manually in an external DOM element, if it is created within a createviewmodel function (or even within a normal component view model, although the MVVM pattern does not work for you?). ) must be removed
      • Of course, you don't have to worry about releasing event handles created using standard knockout bindings in your view, because KO automatically registers them when the elements are removed)
For example:
var someexternalobservable = ko.observable (123);  function Somecomponentviewmodel () {this.mycomputed = ko.computed (function () {return someexternalobservable () +    1;     }, this);    this.mypurecomputed = ko.purecomputed (function () {return someexternalobservable () + 2;     }, this);  This.mysubscription = Someexternalobservable.subscribe (function (val) {console.log (' the external observable changed    To ' + Val);     }, this); This.myintervalhandle = Window.setinterval (function () {Console.log (' another second passed, and the component is St    Ill alive. '); }, 1000);}    SomeComponentViewModel.prototype.dispose = function () {this.myComputed.dispose ();    This.mySubscription.dispose ();    Window.clearinterval (This.myintervalhandle); This.mypurecomputed doesn ' t need to be manually disposed.} Ko.components.register (' Your-component-name ', {viewmodel:somecomponentviewmodel, Template: ' Some template '});

Computed and subscription that rely solely on the same view model object are not strictly required to destroy because this creates a circular reference that the JavaScript garbage collector knows how to release. However, in order to avoid having to remember which things need to be cleaned up, whenever possible, you'd better use purecomputed, whether or not the technology is necessary, to explicitly destroy all other computeds/subscriptions.


Disposal and memory management

Optionally, your ViewModel class may has a dispose function. If implemented, Knockout would call this whenever the component are being torn down and removed from the DOM (e.g., because The corresponding item is removed from a foreach , or is a if binding has become false ).

You must use to dispose release any resources that aren ' t inherently garbage-collectable. For example:

  • setIntervalCallbacks'll continue to fire until explicitly cleared.
    • Use clearInterval(handle) to stop them, otherwise your viewmodel might is held in memory.
  • ko.computedProperties continue to receive notifications from their dependencies until explicitly disposed.
    • If a dependency is on an external object, then being sure to use on .dispose() the computed property, otherwise it (and possibly a LSO your ViewModel) would be a held in memory. Alternatively, consider using apure computed to avoid the need for manual disposal.
  • subscriptions to observables continue to fire until explicitly disposed.
    • If you had subscribed to an external observable, being sure to use on .dispose() the subscription, otherwise the callback (and PO Ssibly also your viewmodel) would be held in memory.
  • manually-created Event handlers on external DOM elements, if created inside a createViewModel function (or even inside a reg Ular component ViewModel, although to fit the MVVM pattern you shouldn ' t) must is removed.
    • Of course, you don ' t has to worry about releasing any event handlers created by standard Knockout bindings in your view, As KO automatically unregisters them when the elements is removed.

For example:

var someExternalObservable = ko.observable(123);function SomeComponentViewModel() {    this.myComputed = ko.computed(function() {        returnsomeExternalObservable() + 1;    },this);     this.myPureComputed = ko.pureComputed(function() {        returnsomeExternalObservable() + 2;    },this);    this.mySubscription = someExternalObservable.subscribe(function(val) {        console.log(‘The external observable changed to ‘+ val);    },this);    this.myIntervalHandle = window.setInterval(function() {        console.log(‘Another second passed, and the component is still alive.‘);    }, 1000);}SomeComponentViewModel.prototype.dispose =function() {    this.myComputed.dispose();    this.mySubscription.dispose();    window.clearInterval(this.myIntervalHandle);    // this.myPureComputed doesn‘t need to be manually disposed.}ko.components.register(‘your-component-name‘, {    viewModel: SomeComponentViewModel,    template: ‘some template‘});

It isn ' t strictly necessary to dispose computeds and subscriptions that's depend on properties of the same ViewModel OB Ject, since this creates only a circular reference which JavaScript garbage collectors know how to release. However, to avoid have to remember which things need disposal, you could prefer to use pureComputed wherever possible, and explic itly Dispose all and computeds/subscriptions whether technically necessary or not.

Knockout component resource cleanup and memory management

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.