Configuring Dojo with dojoConfig - The Dojo Toolkit
转载自Dojo官网
Configuring Dojo with dojoConfig
The dojoConfig object (formerly djConfig) allows you to set options and default behavior for various aspects of the toolkit. In this tutorial we'll explore what's possible and how you can put dojoConfig to use in your code.
- Difficulty: Beginner
- Dojo Version: 1.10
Introduction
The dojoConfig object (known as djConfig prior to Dojo 1.6) is the primary mechanism for configuring Dojo in a web page or application. It is referenced by the module loader, as well as Dojo components with global options. It can further be used as a configuration point for custom applications, if desired.
The old object name of djConfig is deprecated, but any existing code using it will continue to work up until 2.0. At the time of writing, most documentation still uses djConfig; the two names are directly equivalent, but we'll adopt and encourage use of the new dojoConfig name from here on.
Getting Started
Let's run through some quick examples to see how dojoConfig works in practice. First, a programmatic example of setting dojoConfig directly:
<!-- set Dojo configuration, load Dojo --><script>
dojoConfig= {
has: {
"dojo-firebug": true
},
parseOnLoad: false,
foo: "bar",
async: true
};
</script>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.1/dojo/dojo.js"></script>
<script>
// Require the registry, parser, Dialog, and wait for domReady
require(["dijit/registry", "dojo/parser", "dojo/json", "dojo/_base/config", "dijit/Dialog", "dojo/domReady!"], function(registry, parser, JSON, config) {
// Explicitly parse the page
parser.parse();
// Find the dialog
var dialog = registry.byId("dialog");
// Set the content equal to what dojo.config is
dialog.set("content", "<pre>" + JSON.stringify(config, null, "\t") + "</pre>");
// Show the dialog dialog.show();});
</script>
<!-- and later in the page -->
<div id="dialog" data-dojo-type="dijit/Dialog" data-dojo-props="title: 'dojoConfig / dojo/_base/config'">
</div>
Notice that dojoConfig is defined in a script block before dojo.js is loaded. This is of paramount
importance—if reversed, the configuration properties will be ignored.
In this example, we have set three flags: parseOnLoad: false, has (dojo-firebug sub-property), and async: true. Additionally, a custom property has been specified: foo: "bar". For this demo, a dijit/Dialog has been placed in the page. Code that runs from within the require callback converts the value of dojo.config to JSON and places it into the dialog for review. Among the results are our properties: parseOnLoad, has, and foo. But there are also a few others, which are related to the fact that the demo page uses the cross-domain, Google-CDN-hosted version of Dojo 1.10.
It is important to note the distinction between dojoConfig and dojo/_base/config. dojoConfig is purely for input purposes—this is how we communicate configuration parameters to the loader and modules. During the bootstrap process, dojo/_base/config is populated from these parameters for later lookup by module code.
Here's the same example written declaratively:
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.1/dojo/dojo.js"
data-dojo-config="has:{'dojo-firebug': true}, parseOnLoad: false, foo: 'bar', async: 1">
</script>
In this case, we use the same data-dojo-config attribute on the Dojo script element that you've seen in other tutorials and examples. This is entirely functionally equivalent to the previous example. In both cases, the config options we provide are ultimately mixed into the dojo/_base/config object, where they can be retrieved immediately after the bootstrapping process that takes place as dojo.js loads.
You can confirm this by setting some new values in dojoConfig, and checking the dojo.config object in the console. So, dojoConfig is a generic configuration property-bag for Dojo. Lets see what options there are and how we can use them.
has() Configuration
One of the major features added in Dojo 1.7+ was the use of the has() pattern for feature detection. We can specify features for the has() feature set in dojoConfig, by including an object hash of features as the value of the hasproperty. This feature set is now used for determining certain supported capabilities in Dojo. For example, we could disable the amd factory scan (scanning the module for CommonJS require(module) statements to load as deps) with:
<script>
dojoConfig = {
has: {
"dojo-amd-factory-scan": false
}
};
</script>
Debug/Firebug Lite Configuration
You may be familiar by now with the isDebug config flag from other tutorials or usage of Dojo in versions prior to Dojo 1.7, to explicitly enable debug information. In Dojo 1.7+, this is now also specified with a has() feature at a higher level of granularity. To enable debugging assistance with Firebug Lite for older versions of Internet Explorer, we can set the dojo-firebug feature (isDebug can still be used to load this, but using the feature will load earlier in the loading cycle in async mode). If you have Firebug or another console available and open, it does nothing. But if you don't have a console, it will load Dojo's version of Firebug Lite, and create the console UI at the bottom of the page. This can be handy when debugging in earlier versions of IE or other browsers without nice developer tools.
To enable debugging messages for deprecated and experimental features, we can set dojo-debug-messages to true (this defaults to false, unless you have set isDebug). if this feature is set to false, these warnings will be suppressed. For example, to enable a developer console (browser provided or use Firebug Lite) and log debugging messages:
<script>dojoConfig = {has: {"dojo-firebug": true,"dojo-debug-messages": true}};</script>
To disable a guaranteed console object, we can set dojo-guarantee-console feature to false. This feature defaults to true and will create a dummy
consoleobject if necessary so that anyconsole.*logging statements in your code safely and quietly execute without throwing exceptions.
The following additional options are available to further configure this in-page console:
debugContainerId: specify a particular element to contain the console UIpopup: use a popup window rather than rendering the console into the current window
Loader Configuration
Dojo received a new loader in Dojo 1.7 to accommodate for the toolkit's new AMD module format. This new loader added a few new configuration options that are crucial to defining packages, maps, and more. For details on the loader, see the Advanced AMD Usage tutorial. Important loader configuration parameters include:
baseUrl: The base URL prepended to a module identifier when converting it to a path or URL.baseUrl: "/js"packages: An array of objects which provide the package name and location:packages: [{name: "myapp",location: "/js/myapp"}]map: Allows you to map paths in module identifiers to different paths:map: {dijit16: {dojo: "dojo16"}}paths: a map of module id fragments to file paths:var dojoConfig = {packages: ["package1","package2"],paths: {package1: "../lib/package1",package2: "/js/package2"}};// ...is equivalent to:var dojoConfig = {packages: [{ name: "package1", location: "../lib/package1" },{ name: "package2", location: "/js/package2" }]};async: Defines if Dojo core should be loaded asynchronously. Values can betrue,falseorlegacyAsync, which puts the loader permanently in legacy cross-domain mode.async: trueparseOnLoad: If true, parses the page withdojo/parserwhen the DOM and all initial dependencies (including those in thedojoConfig.depsarray) have loaded.parseOnLoad: trueIt is recommended that
parseOnLoadbe left at false (it defaults to false, so you can simply omit this property), and that developers explicitly requiredojo/parserand callparser.parse().deps: An array of resource paths which should load immediately once Dojo has loaded:deps: ["dojo/parser"]callback: The callback to execute oncedepshave been retrieved:callback: function(parser) {// Use the resources provided here}waitSeconds: Amount of time to wait before signaling load timeout for a module; defaults to 0 (wait forever):waitSeconds: 5cacheBust: If true, appends the time as a querystring to each module URL to avoid module caching:cacheBust: true
Now let's create a simple demo that puts the basic parameters to use. One very common scenario is using Dojo Toolkit from CDN with local modules. Let's say we use Google CDN with modules in the/documentation/tutorials/1.10/dojo_config/demo space:
<!-- Configure Dojo first --><script>dojoConfig = {has: {"dojo-firebug": true,"dojo-debug-messages": true},// Don't attempt to parse the page for widgetsparseOnLoad: false,packages: [// Any references to a "demo" resource should load modules locally, *not* from CDN{name: "demo",location: "/documentation/tutorials/1.10/dojo_config/demo"}],// Timeout after 10 secondswaitSeconds: 10,map: {// Instead of having to type "dojo/domReady!", we just want "ready!" instead"*": {ready: "dojo/domReady"}},// Get "fresh" resourcescacheBust: true};</script><!-- Load Dojo, Dijit, and DojoX resources from Google CDN --><script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.1/dojo/dojo.js"></script><!-- Load a "demo" module --><script>require(["demo/AuthoredDialog", "dojo/parser", "ready!"], function(AuthoredDialog, parser) {// Parse the pageparser.parse();// Do something with demo/AuthoredDialog...});</script>By using the
packagesconfiguration, we've made all references todemo/*point to our local/documentation/tutorials/1.10/dojo_config/demo/directory, while allowing any references todojo,dijit, anddojoxto come from Google CDN. Had thedemopackage not been defined, the request fordemo/AuthoredDialogwould have gone to//ajax.googleapis.com/ajax/libs/dojo/1.10.1/dojo/demo/AuthoredDialog.js. We also used alias, by associatingreadywithdojo/domReady.
Extensive documentation about the new loader provides even more details.
The new loader also supports the legacy dojo.require() resource loading and configuration properties likemodulePaths covered in this same tutorial for Dojo 1.6, thus allowing developers to safely upgrade existing applications easily and without worry.
Locale and Internationalization
Dojo's i18n system is documented in its own right, and worthy of its own tutorial, but we'll touch on it here just to show dojoConfig at work again.
You can configure the locale to use for any widgets or localized content using Dojo's i18n infrastructure fromdojoConfig. The locale option lets you override the default provided to Dojo by your browser. A simple demo shows it at work:
<script>var dojoConfig = {has: {"dojo-firebug": true,"dojo-debug-messages": true},parseOnLoad: true,// look for a locale=xx query string param, else default to 'en-us'locale: location.search.match(/locale=([\w\-]+)/) ? RegExp.$1 : "en-us"};</script><script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.1/dojo/dojo.js"></script><script>require(["dojo/date/locale", "dijit/Dialog", "dojo/json", "dojo/_base/config","dojo/_base/window", "dojo/i18n", "dojo/domReady!"], function(locale, Dialog, JSON, config, win) {var now = new Date();var dialog = new Dialog({id: "dialog",// set a title on the dialog of today's date,// using a localized date formattitle: "Today: " + locale.format(now, {formatLength:"full",selector:"date"})}).placeAt(win.body());dialog.startup();dialog.set("content", "<pre>" + JSON.stringify(config, null, "\t") + "</pre>");dialog.show();});</script>
In the demo, where we define the locale property of the dojoConfig object, we look for a locale=xx parameter from the query string. That's a demo artifact; typically you might hard-code the locale. Setting the locale ahead of any module loading ensures that the correct localized message bundle dependencies are loaded where necessary. In this case, we use the dojo/date/locale module to format a date object to a localized string for the Dialog title.
For multi-lingual pages, you will need to load bundles for the other locales as well as the one specified by your browser or the dojoConfig.locale property. In this case, use the extraLocale config property, with an array of string locale names.
When using the dojo/parser, the lang= setting on an ancestor DOMNode overrides the dojoConfig.localesetting. This behavior will change in Dojo 2.0. You can also specify the lang for individual widgets, overriding thedojoConfig.locale setting for only that widget.
Custom Properties
Because dojo.config is always known to exist, and is the logical place to provide for page-scoped configuration, several other modules in Dojo use it for their own particular configuration properties. We see this in Dijit, and especially in DojoX, where module flags and behavior can be set:
- Dijit Editor
- allowXdRichTextSave
- dojox GFX
- dojoxGfxSvgProxyFrameUrl, forceGfxRenderer, gfxRenderer
- dojox.html metrics
- fontSizeWatch
- dojox.io transports and plugins
- xipClientUrl, dojoCallbackUrl
- dojox.image
- preloadImages
- dojox.analytics plugins
- sendInterval, inTransitRetry, analyticsUrl, sendMethod, maxRequestSize, idleTime, watchMouseOver, sampleDelay, targetProps, windowConnects, urchin
- dojox.cometd
- cometdRoot
- dojox.form.FileUploader
- uploaderPath
- dojox.mobile
- mblApplyPageStyles, mblHideAddressBar, mblAlwaysHideAddressBar, mobileAnim, mblLoadCompatCssFiles
What works for dojox modules also works for your own applications and modules. dojoConfig is an ideal place to provide configuration for behavior and page- or application-wide properties. Consider the following:
<script>dojoConfig = {has: {"dojo-firebug": true},app: {userName: "Anonymous"}};</script><script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.1/dojo/dojo.js"></script><script>require(["dijit/Dialog", "dijit/registry", "dojo/parser", "dojo/_base/lang","dojo/json", "dojo/_base/config", "dojo/io-query", "dojo/domReady!"], function(Dialog, registry, parser, lang, JSON, config, ioQuery) {// pull configuration from the query string// and mix it into our app configvar queryParams = ioQuery.queryToObject(location.search.substring(1));lang.mixin(config.app, queryParams);// Create a dialogvar dialog = new Dialog({title: "Welcome back " + config.app.userName,content: "<pre>" + JSON.stringify(config, null, "\t") + "</pre>"});// Draw on the app config to put up a personalized messagedialog.show();});</script>
In this example, we've tacked on an "app" dojoConfig property, which we later reference via dojo.config to put up a personalized greeting in the Dialog. There are many ways to approach populating dojoConfig.app. It can be pre-populated with reasonable defaults and mixed-in with specific values later. In production, the dojoConfigscript block might get written out on the server-side. Alternatively, you could populate it from a cookie with JSON-formatted configuration values, or—as in our earlier example—you could extract configuration data straight from the query string. In development and test mode, you could use a template that provides dummy values, or load a script or module that populates it.
Conclusion
In this tutorial, we've covered many common ways in which dojo.config can be populated—via dojoConfig ordata-dojo-config—and how its values influence behavior and supply properties to Dojo modules.
The well-defined position and role dojo.config has in the Dojo bootstrap and lifecycle means that the same concept applies neatly to Dojo modules and even your own modules and applications.
Colophon
Configuring Dojo with dojoConfig - The Dojo Toolkit的更多相关文章
- 使用dojoConfig配置dojo(翻译)
http://dojotoolkit.org/documentation/tutorials/1.10/dojo_config/index.html dojoConfig对象(原来是djConfig对 ...
- Dojo入门:初识Dojo
Dojo的全称是Dojo Toolkit,始创于2004年,是当前各种蓬勃发展的JS工具包中的佼佼者.Dojo 为富互联网应用程序(RIA) 的开发提供了完整的端到端的解决方案,包括核心的 Jav ...
- dojo 九 effects dojo/_base/fx 和 dojo/fx
官方教程:Dojo Effects这里讲学习一下dojo如何实现淡入.淡出.滑动等效果.实现这些特殊的效果有两个包 dojo/_base/fx 和 dojo/fx.dojo/_base/fx 中提供了 ...
- Dojo初探之3:dojo的DOM操作、query操作和domConstruct元素位置操作(基于dojo1.11.2版本)
前言: 前面两章讲了dojo的基本规范和配置,当然这个配置不是必须的,当你有这需求的时候就可以用到dojo的config配置. dojo的所有js都是符合AMD规范进行异步加载的:http://blo ...
- dojo/Deferred类和dojo/promise类的使用
参考博客:https://blog.csdn.net/blog_szhao/article/details/50220181 https://dojotoolkit.org/docume ...
- Dojo的ready函数:dojo.ready(以前的dojo.addOnLoad)
dojo的dojo/domReady!插件和dojo/ready的区别: In simple cases,dojo/domReady! should be used. If an app us ...
- Dojo的dojoConfig函数
在我们引入 Dojo 的时候都会先做一些全局的配置,所使用的就是 Dojo 的 Config 接口. dojoConfig为以前的dgConfig函数. <script type="t ...
- Dojo 学习笔记 之 Dojo hitch&partial
原文: http://dojotoolkit.org/documentation/tutorials/1.10/hitch/index.html 版本: Dojo 1.10 为了更好地使用JavaSc ...
- dojo 六 使用query dojo/query
要使用query,就要引入dojo/query包.query可以根据Dom里节点的标签名.id名.class名来检索一个或多个节点.---------------------------------- ...
随机推荐
- BZOJ2754: [SCOI2012]喵星球上的点名(AC自动机)
Time Limit: 20 Sec Memory Limit: 128 MBSubmit: 2816 Solved: 1246[Submit][Status][Discuss] Descript ...
- 转载:Spring使用p名称空间配置属性
这篇博客简明扼要地介绍了Spring中p命名空间的使用,笔者在此转载一下. 原文链接:https://blog.csdn.net/liaomin416100569/article/details/49 ...
- Mysql8.0 3306端口无法远程连接
在阿里云上搭建MySql8.0数据库服务,在阿里云上可以成功连接登陆使用,但用自己的电脑远程连接时却无法成功连接 经过资料查找,找出原因如下: 1.首先通过查看MySQL的的用户信息 可以看到host ...
- git 上传到码云
创建分支 在码云里创建好分支 命令行进入项目所在的目录 显示码云上的分支 git pull 选择将要编辑的分支(index-fenzhi) git checkout index-fenzhi 查看分支 ...
- vue.js 组件-全局组件和局部组件
这两天学习了Vue.js 感觉组件这个地方知识点挺多的,而且很重要,所以,今天添加一点小笔记. 首先Vue组件的使用有3个步骤,创建组件构造器,注册组件,使用组件3个方面. 代码演示如下: <! ...
- jquery easyui alert闪一下的问题
最近做项目使用了 jQuery EasyUI,版本是 1.4.3.x,在使用alert方法的时候如果alert后面执行页面跳转的话alert的消息只会闪一下,就跳到其他页面了 $.messager.a ...
- mysql根据二进制日志恢复数据/公司事故实战经验
根据二进制日志恢复 目的:恢复数据,根据二进制日志将数据恢复到今天任意时刻 增量恢复,回滚恢复 如果有备份好的数据,将备份好的数据导入新数据库时,会随着产生二进制日志 先准备一台初始化的数据库 mys ...
- go web处理上传
要使表单能够上传文件,第一步就是添加form的enctype属性,enctype属性有如下三种情况: application/x-www-form-urlencoded 表示在发送前编码所有字符(默认 ...
- 毕业2年 Summary
本文同时发表在https://github.com/zhangyachen/zhangyachen.github.io/issues/135 看了下去年写毕业一周年总结的时间:2017-6-16,今天 ...
- Failed to read candidate component class错误分析
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component c ...