我似乎无法获得有关 declare to work 的 dojo 示例。示例链接:http://dojotoolkit.org/reference-guide/1.9/dojo/_base/declare.html#id3
我是这样设置的:
/index.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.9.2/dojo/dojo.js" data-dojo-config="async: true"></script>
<script src="/my/Employee.js"></script>
<script src="/my/Person.js"></script>
<script>
var dojoConfig = {
parseOnLoad: true,
packages: [{
"name": "my",
"location": location.pathname.replace(/\/[^/]+$/, "") + "/my"
}
]
};
</script>
<script>
require(["my/Person"], function (Person)
{
var folk = new Person("phiggins", 42, "Tennessee");
});
require(['my/Employee'], function (Employee)
{
var matt = new Employee("Matt", 33, "California", 1000);
console.log(kathryn.askForRaise(), matt.askForRaise()); // 3600, 20
});
</script>
<title></title>
</head>
<body>
</body>
</html>
/我的/Person.js
define(["dojo/_base/declare"], function (declare)
{
return declare(null, {
constructor: function (name, age, residence)
{
this.name = name;
this.age = age;
this.residence = residence;
}
});
});
/my/Employee.js
define(["dojo/_base/declare", "my/Person"], function (declare, Person)
{
return declare(Person, {
constructor: function (name, age, residence, salary)
{
// The "constructor" method is special: the parent class (Person)
// constructor is called automatically before this one.
this.salary = salary;
},
askForRaise: function ()
{
return this.salary * 0.02;
}
});
});
我试图在所有回调方法中设置一个断点(return declare ...),但它永远不会进入那里。它也永远不会进入 require block 的回调。
感谢任何帮助
最佳答案
您的 HTML 文件只有几个小问题。
在加载 Dojo 的脚本标记中,您添加了 data-dojo-config
属性。这是告诉 Dojo 它应该如何表现的两种方法之一——另一种方法是定义一个全局 dojoConfig
对象。你两样都做到了!因此,删除 data-dojo-config
属性。
现在,Dojo 需要在加载时了解配置对象。所以 dojoConfig
必须在加载 Dojo 的脚本标签之前定义。由于 async:true
刚刚被删除,因此将其添加到配置对象中。
此外,正如 Buffalo 所提到的,没有必要将 Person 和 Employee 模块包含在脚本标签中。 Dojo 使用称为 AMD(异步模块定义)的模式来加载模块。基本上就是您随处可见的 define
和 require
函数。它们通过非常方便地为您插入脚本标记来加载模块(只要您告诉它们在 dojoConfig
中的何处可以找到您的命名空间)。
所以你脑袋的开头应该是这样的:
<script>
var dojoConfig = {
parseOnLoad: true,
async: true,
packages: [{
"name": "my",
"location": location.pathname.replace(/\/[^/]+$/, "") + "/my"
}]
};
</script>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.9.2/dojo/dojo.js"></script>
实际上,这就是让 Dojo 加载您的类所需的全部内容。但是,我认为您可能需要注意另一个小问题:
首先,您需要 Person 模块。 Dojo 将在幕后执行其模块加载魔法,并在完成后调用 function(Person) {...}
。接下来,您对 Employee 模块执行相同的操作并调用 function(Employee) {... }
。您应该记住,您不能保证 function(Person)
在 function(Employee)
之前被调用。例如,如果您加载了 Person 和 100 个其他模块,将首先调用 function(Employee)
。
(我提到这一点是因为我怀疑 kathryn 是一个打字错误,并且您打算改用 folk 对象。我现在知道情况可能并非如此,但无论如何我都会把它留在这里)。
关于javascript - dojo - 声明函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21053561/