In today's long-lived JavaScript apps it is essential to not introduce memory leaks within your custom components. Dojo Toolkit to the rescue: The dijit/Destroyable module addresses this problem and makes it really easy to track the various handles of an instance. Various components such as dojo/aspectdojo/topicdojo/ondojo/Stateful and dojo/store/Observable return a handle which can be passed to dijit/Destroyable's own() method. The application must then call destroy() on the instance in order to release the handles.

Here's an example demonstrating the tracking of some handles and how to have them removed at the end of the components lifecycle:

Our layout

+ source.html
+ mylib
+ app.js
+ ChildWidget.js
+ MainWidget.js
+ templates
+ MainWidget.html

MainWidget.js

This is the main widget which makes use of events, aspects, topics etc. It tracks all its handles by passing them to own():

define([
"dojo/_base/declare",
"dijit/_WidgetBase",
"dijit/_TemplatedMixin",
"dojo/aspect",
"dojo/topic",
"dojo/on",
"dojo/Stateful",
"dojo/store/Memory",
"dojo/store/Observable",
"./ChildWidget",
"dojo/text!./templates/MainWidget.html"
], function (
declare,
WidgetBase,
TemplatedMixin,
aspect,
topic,
on,
Stateful,
Memory,
Observable,
ChildWidget,
template
) {
return declare([WidgetBase, TemplatedMixin], { templateString: template, // constructor args
timeout: null,
leaky: false, postCreate: function () {
this.setChildWidget();
this.setAspect();
this.setEvent();
this.setSubscription();
this.setStateful();
this.setObservable();
}, setChildWidget: function () {
var widget = new ChildWidget({ timeout: this.timeout }); if(!this.leaky) {
// register widget.destroy() to be called when this widget is destroyed
this.own(widget);
}
}, setAspect: function () {
var someObject = {
someMethod: function () {}
}, signal = aspect.after(someObject, 'someMethod', function () {
console.warn('aspect.after');
}); if(!this.leaky) {
// register signal.remove() to be called when this widget is destroyed
this.own(signal);
} // call someObject.someMethod() after this widget has been destroyed
setTimeout(function() {
someObject.someMethod();
}, this.timeout);
}, setEvent: function () {
var handle = on(this.clickableNode, 'click', function (ev) {
console.warn('on');
}); if(!this.leaky) {
// register handle.remove() to be called when this widget is destroyed
this.own(handle);
}
}, setSubscription: function () {
var subscription = topic.subscribe('some-topic', function (data) {
console.warn('topic.subscribe');
}); if(!this.leaky) {
// register subscription.remove() to be called when this widget is destroyed
this.own(subscription);
} // publish a topic after this widget has been destroyed
setTimeout(function() {
topic.publish('some-topic', {});
}, this.timeout);
}, setStateful: function () {
var stateful = new Stateful({ a: 'aaa' }), handle = stateful.watch('a', function (name, oldVal, newVal) {
console.warn('Stateful');
}); if(!this.leaky) {
// register handle.remove() to be called when this widget is destroyed (handle.unwatch() is deprecated)
this.own(handle);
} // modify a property after this widget has been destroyed
setTimeout(function() {
stateful.set('a', 'AAA');
}, this.timeout);
}, setObservable: function () {
var store = Observable(new Memory({
data: [{ id: 0, a: 'aaa' }]
})), result = store.query(), observer = result.observe(function (item, removedIndex, insertedIndex) {
console.warn('Observable');
}, true); if(!this.leaky) {
// register observer.remove() to be called when this widget is destroyed (observer.cancel() is deprecated)
this.own(observer);
} // add an item after this widget has been destroyed
setTimeout(function() {
store.put({ id: 1, b: 'bbb' });
}, this.timeout);
}
});
});

  

ChildWidget.js

A widget without DOM representation:

define([
"dojo/_base/declare",
"dijit/_WidgetBase"
], function (
declare,
WidgetBase
) {
return declare([WidgetBase], { timeoutId: null, // constructor args
timeout: null, postCreate: function () {
this.timeoutId = setTimeout(function () {
console.warn('child widget');
}, this.timeout);
}, destroy: function () {//alert('destroy')
this.inherited(arguments);
clearTimeout(this.timeoutId);
}
});
});

  

app.js

The entry point into the application:

define([
"./MainWidget",
"dojo/domReady!"
], function (MainWidget) { var timeout = 3000, widget = new MainWidget({
timeout: timeout,
leaky: false // this is just to demonstrate the behaviour of a leaky widget
}, 'widget'); widget.startup(); setTimeout(function () {
widget.destroy(true);
console.info('Widget is now destroyed while preserving the dom')
}, timeout - 1000); // destroy widget one second before the various potentially leaky handles in the widget are executed
});

  

source.html

... and finally the HTML page to bootstrap our application:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Destroyable</title>
<script>
var dojoConfig = {
async: true,
cacheBust: 1,
packages: [
{ name: 'mylib', location: 'path/to/mylib' } // relative to dojo/dojo.js
]
};
console.log('SOURCE');
</script> <script src="path/to/dojo/dojo.js"></script><!-- relative to this document --> <script>
require(['mylib/app']);
</script>
</head>
<body>
<div class="document">
<div id="widget"></div>
</div>
</body>
</html>

  

Using dijit/Destroyable to build safe Components的更多相关文章

  1. [Recompose] Configure Recompose to Build React Components from RxJS Streams

    Recompose provides helper functions to stream props using an Observable library of your choice into ...

  2. 5、二、App Components(应用程序组件):0、概述

    二.App Components(应用程序组件) 0.概述   App Components Android's application framework lets you create rich ...

  3. Open Harmony移植:build lite配置目录全梳理

    摘要:本文主要介绍build lite 轻量级编译构建系统涉及的配置目录的用途,分析相关的源代码. 本文分享自华为云社区<移植案例与原理 - build lite配置目录全梳理>,作者:z ...

  4. 转:分享13款PHP开发框架

    文章来自于:http://mashable.com/2014/04/04/php-frameworks-build-applications/ Building software applicatio ...

  5. 安装MySQL的时候遇到的错误

    这里我安装的是MySQL5.6 我遇到的错误有 (1)Warning: Bison executable not found in PATH 解决办法: yum install bison 原文摘自: ...

  6. REACT day 1

    https://facebook.github.io/react/ A JAVASCRIPT LIBRARY FOR BUILDING USER INTERFACES Declarative view ...

  7. 《静静的dojo》 总体教程介绍

    web2.0时代,ajax技术成为整个前端开发领域的基石.大部分的书籍.博客由此切入来介绍前端类库与框架,所以dojo往往只被当做一个ajax类库来介绍,然而仅仅以此来定位dojo,无异于管中窥豹.对 ...

  8. centos 7.0 编译安装mysql 5.6.22 再次总结 成功编译安装~ 越来越熟练了~

    查找php.ini文件所在位置 [root@localhost /]# find -name php.ini ./usr/etc/php/etc/php.ini mysql官网的安装说明http:// ...

  9. centos6.5环境源码编译安装mysql5.6.34

    centos6.5环境源码编译安装mysql5.6.34 源码下载地址http://dev.mysql.com/downloads/mysql/5.6.html#downloads 选择Generic ...

随机推荐

  1. 几种jQuery 实现无限滚动的插件

    1.EndLess Scroll 2.infinite-scroll插件的使用

  2. EF6 CodeFirst+Repository+Ninject+MVC4+EasyUI实践(三)

    前言 在上一篇中,我们依靠着EasyUI强大的前端布局特性把前端登录界面和主界面给搭建完成了.这一篇我们就要尝试着把整个解决方案部署到云端呢,也就是Visual Studio Online(TFVC) ...

  3. ubuntu下部署SVN

    sudo apt-get install subversion 创建库文件夹 sudo mkdir svn sudo chown -R 777 svn 设置为所有用户配置777权限 sudo chmo ...

  4. iis里面浏览网页,提示找不到应用程序的解决办法

    iis配置成功,数据库链接正确,代码无误,在iis里面,浏览某网页,提示找不到应用程序,这时一下子懵了. 处理办法:在浏览器中直接输入网址,例如:http://192.168.1.111,这时能够打开 ...

  5. 4412开发板升级4.2之后改了logo开机后屏幕闪解决办法

    荣品4412开发板升级到4.2请注意增加虚拟机内存. 问:荣品4412开发板升级到Android4.2之后,改了logo.4412板子开机后,过一会屏幕就一闪一闪,是什么原因? Android4.2编 ...

  6. 那些年因为粗心导致的外链css无效

    css文件三种引用的三种方式: 1.外链: <link rel= "stylesheet" href=""> 注:如果使用外链式绝对不可以忘记 re ...

  7. xcode6.0以上创建一个Empty Application

    运行Xcode 6,创建一个Single View Application工程.   创建好后,把工程目录下的Main.storyboard和LaunchScreen.xib删除,扔进废纸篓.   打 ...

  8. SpringMVC与MyBatis整合(一)——查询人员列表

    从今天开始,一点点的记录做毕设和学习的过程. 寒假才开始接触SpringMVC和MyBatis,之前对框架的概念理解并不到位,也没学过Spring.目前学习起来思路并不很清晰,有些东西我还不能理解,只 ...

  9. SQL 常用函数

    --将字符串中从某个字符开始截取一段字符,然后将另外一个字符串插入此处  select stuff('hi,world!',4,4,'****') --返回值hel****orld!  --返回从指定 ...

  10. js动画之多物体运动

    多个物体这不能使用一个定时器了,要给每个物体一个定时器 <!DOCTYPE html> <html lang="en"> <head> < ...