从 jquery 范围调用到 class 函数
from jquery scope call to class function
我想从 Jquery 范围(在同一个 class 中)调用同一个 class function/method。我该怎么办?
我试过了:
displayTemplate.findWithAttr(action);
或
this.findWithAttr(action);
回应
"this.findWithAttr is not a function"
这是我的代码。
class displayTemplate{
findWithAttr(action) {
//to do something with action
}
router(action){
if(action == "something"){
$( "#confirm_dialog_msg" ).text("text?");
$( "#dialog-confirm" ).dialog({
buttons: {
"yes": function() {
$( this ).dialog( "close" );
//how in this area call to "findWithAttr" function above?
this.findWithAttr(action);
},
"No": function() {
//..
}
}
});
}
//...
}
}
在进入函数的 JQuery 范围之前,像这样声明一个变量
var self = this;
然后只需执行 self.findWithAttr
就可以了。
很喜欢:
router(action){
if(action == "something"){
var self = this;
$( "#confirm_dialog_msg" ).text("text?");
$( "#dialog-confirm" ).dialog({
buttons: {
"yes": function() {
$( this ).dialog( "close" );
//how in this area call to "findWithAttr" function above?
self.findWithAttr(action);
},
"No": function() {
//..
}
}
});
}
希望对您有所帮助。
您可能想要使用 lambda 表达式而不是嵌套函数。
它们之间的区别之一是 lambda 表达式保留父上下文而不是拥有自己的上下文。
因此,您只需更改
"yes": function() {
到
"yes": () => {
我想从 Jquery 范围(在同一个 class 中)调用同一个 class function/method。我该怎么办?
我试过了:
displayTemplate.findWithAttr(action);
或
this.findWithAttr(action);
回应
"this.findWithAttr is not a function"
这是我的代码。
class displayTemplate{
findWithAttr(action) {
//to do something with action
}
router(action){
if(action == "something"){
$( "#confirm_dialog_msg" ).text("text?");
$( "#dialog-confirm" ).dialog({
buttons: {
"yes": function() {
$( this ).dialog( "close" );
//how in this area call to "findWithAttr" function above?
this.findWithAttr(action);
},
"No": function() {
//..
}
}
});
}
//...
}
}
在进入函数的 JQuery 范围之前,像这样声明一个变量
var self = this;
然后只需执行 self.findWithAttr
就可以了。
很喜欢:
router(action){
if(action == "something"){
var self = this;
$( "#confirm_dialog_msg" ).text("text?");
$( "#dialog-confirm" ).dialog({
buttons: {
"yes": function() {
$( this ).dialog( "close" );
//how in this area call to "findWithAttr" function above?
self.findWithAttr(action);
},
"No": function() {
//..
}
}
});
}
希望对您有所帮助。
您可能想要使用 lambda 表达式而不是嵌套函数。 它们之间的区别之一是 lambda 表达式保留父上下文而不是拥有自己的上下文。
因此,您只需更改
"yes": function() {
到
"yes": () => {