你好我刚开始学习道场,我该如何使用this
对象?我已经创建了类似下面的东西,但我认为它不正确
var node = dojo.query('.verticalslider')[0];
dojo.connect(node, "onclick", function(){
var c = dojo.query(this).parent();
console.log(c);
})
你好我刚开始学习道场,我该如何使用this
对象?我已经创建了类似下面的东西,但我认为它不正确
var node = dojo.query('.verticalslider')[0];
dojo.connect(node, "onclick", function(){
var c = dojo.query(this).parent();
console.log(c);
})
固定代码:
// eventlistener is setup on every DOM node with className 'verticalslider'
dojo.query('.verticalslider').connect("click", function(){
// this references the clicked DOM node
var c = this.parentNode
// parentNode of the clicked DOM node with class 'vertical..'
console.log(c);
})
这更像是一个一般的 js 问题,然后它是一个道场,但对于 .connect 和 .on 函数,以下适用:
dojo.connect 是一个用于创建事件监听器的包装器。通常,如果您编写像 node.foo = function() {} 这样的代码,您只能拥有一个功能,因为等号会覆盖现有的功能。.connect 的标准行为是适用相同的范围,因此“this”引用我们正在侦听的对象。在这种情况下,“节点”。
dj.connect(node, "foo", function() { this == node evaluates to true and arguments[0] == event });
dojo.hitch (dojo/_base/lang) 是一个作用域附加助手。它适用于除超时/间隔挂钩之外的任何事件,并将强制传递给的函数对象,比如 .connect,在给定的范围内运行:dojo.hitch(scope, functor)。
dj.connect(node, "bar", dj.hitch(dojo.doc(), function() { this == window.document evals true }));
就 dojo.query 而言,它会返回一个 NodeList。列表不能有一个父级,因此您的 dojo.query(node).parent() 是错误的。.query 的正确用法是将选择器作为您的第一次使用传递。像这样:
dj.query(
/* String */ "CSS Selector",
/* Optional DOM node, defaults to body */ contextNode
) // => dojo.NodeList
上面提到的代码是直接的方法,但是如果您需要在任何函数/回调中使用 this 的上下文,请使用 dojo.hitch (<1.7) 或 lang.hitch (1.7+)。它在函数内部传递 this 的上下文。
例如:
var myObj = {
foo: "bar"
};
var func = dojo.hitch(myObj, function(){
console.log(this.foo);
});
这里函数内部的 this 指的是对象 myObj 的上下文。
您的另一个固定代码可以是:
var node = dojo.query('.verticalslider')[0];
dojo.connect(node, "onclick", dojo.hitch(this,function(){
var c = dojo.query(this).parent(); // here this will be having the outside context .
console.log(c);
}))