dojo1.7及以后版本插件说明和自定义插件

来源:互联网 发布:2006科比季后赛数据 编辑:程序博客网 时间:2024/04/28 23:53

约定:文章中的loader指的是AMD loader。

dojo 插件是dojo的一个模块,可用于扩展dojo的loader,使得loader可以支持加载非AMD模块,例如模板文件和国际化文件等。

dojo1.7开始包含的插件有如下几个:
1、dojo/domReady:等待DOM结构创建完成再执行回调函数。

例子:

require(["dojo/domReady!"], function(){ // will not be called until DOM is ready});

2、dojo/text:从指定文件(URL)加载字符串,他替待了dojo之前版本的dojo/cache()。他将加载文本资源之后将它作为参数传递给define或者require的回调函数。是requirejs文本加载插件的超集。用法可参见dojo组件中模板的加载。


3、dojo/i18n:加载国际化文件,可向后兼容(兼容非AMD)。是requirejs i18n插件的超集。


4、dojo/has:提供标准化的特征检测。基于has.js项目(见github https://github.com/phiggins42/has.js)。

例子:

define(["dojo/has"], function (has) {if (has("dom")) {// Do something based on feature}});require(["dojo/has!feature?package/module:package/other"], function (featureModule) {// If feature is true, package/module loaded// If feature is false, package/other loaded});

5、dojo/load(在dojo1.8.0中没找到该插件的存在):a convenience plugin for loading dependencies computed at runtime.


6、dojo/require:加载遗留模块,就是之前版本中的dojo.require。


7、dojo/loadInit:causes dojo.loadInit callbacks then other legacy API functions to be executed--in particular dojo.require[After]If--that are associated with a module


当一个传递给require或者define的模块标识符包含“!”的时候,loader将叹号前的字符串作为模块标识符,将叹号后边的作为参数传递给该插件处理。与其他所有的AMD模块一样的是插件模块仅仅被加载一次,与其他模块不同的是他必须返回一个包含load方法的对象。load方法的签名是:

load(id /*the string to the right of the !*/,require /*AMD require; usually a context-sensitive require bound to the module making the plugin request*/,callback /*the function the plugin should call with the return value once it is done*/)->undefined

与常规模块返回值不同的是,loader不缓存插件的callbak函数传递的值(Unlike the value returned by regular modules, the loader does not cache the value passed by a plugin to callback)。插件可以维护自己的内部缓存。例如:

define(["dojo"], function (dojo) {var cache = {};return {load : function (id, require, callback) {var url = require.toUrl(id);if (url in cache) {callback(cache[url]);} else {dojo.xhrGet({url : url,load : function (text) {callback(cache[url] = text);}});}}};});