define(["dojo/text!./path/some.txt"], function(textData) {
Dojo's AMD loader has some useful contextual loading features.
Note the exclamation mark in the dependency.
dojo/text!
can be used to load character data;
dojo/has!
can be used to load different modules based on
environment.
Writing your own plugin is relatively trivial.
An XML loader plugin
This sample module can be used to load data from an XML file with caching.
/* resources/xml.js */ define(["dojo/_base/xhr"], function (xhr) { "use strict"; var cache = {}; return { load : function (id, require, callback) { if(cache[id]) { callback(cache[id]); } xhr.get({ url : require.toUrl(id), handleAs : "xml", load : function(doc){ cache[id] = doc; callback(doc); } }); } }; });
Writing a JSON loader is as simple as changing the handleAs
property.
Usage
Some sample XML:
<?xml version="1.0" encoding="UTF-8"?> <!-- resources/tests/test.xml --> <root> <branch>We come bearing angle-brackets.</branch> </root>
A DOH unit test utilizing the plugin:
/* resources/tests/xmlTests.js */ define(["doh", "dojo/query", "resources/xml!./test.xml"], function(doh, query, doc) { "use strict"; doh.register("resources.tests.xmlTests", [{ name: "xmlTest", runTest: function(){ var list = query("branch", doc); var text = list[0].firstChild.nodeValue; doh.assertEqual("We come bearing angle-brackets.", text); } }]); });
Code was written and tested against Dojo 1.7.
This is really helpful - thanks.
ReplyDeleteDid you find this out through reverse engineering? I can't find docs on this anywhere.
There's some documentation in the AMD loader plugins section. See the Dojo Plugins livedocs.
Delete