我不知道为什么只有当按下按钮时才能运行的功能.
这是我的按钮声明:
var oButton = new sap.m.Button({
id: "buttonId",
text: "Yes",
press: this.fnB()
});
Run Code Online (Sandbox Code Playgroud)
我的控制器如下所示:
sap.ui.controller("<controller-name>", {
fnA: function(){<button_declaration_here>},
fnB: function(){console.log("Hello from fnB!");}
});
Run Code Online (Sandbox Code Playgroud)
当我运行应用程序时,我得到:
你好fnB!
未捕获的TypeError:无法读取未定义的属性"0"
还没有按下按钮,为什么我会收到问候消息?
如果重要,我使用SAP WEB IDE ...
这个:
press: this.fnB()
Run Code Online (Sandbox Code Playgroud)
调用 this.fnB()并使用其返回值初始化press属性,完全是x = foo() 调用 foo和分配其返回值的方式x.
你可能想要
press: this.fnB
Run Code Online (Sandbox Code Playgroud)
要么
press: this.fnB.bind(this)
Run Code Online (Sandbox Code Playgroud)
这样你就可以为函数分配一个引用press,而不是调用它并使用它的返回值.
第二个例子可能需要一些解释:如果我们只使用
press: this.fnB
Run Code Online (Sandbox Code Playgroud)
这将分配的功能press,但它运行时,在this通话过程中fnB也不会一样this在上面的代码,因为在JavaScript中,价值this函数内通常是由函数是怎么被调用确定.
使用Function#bind:
press: this.fnB.bind(this)
Run Code Online (Sandbox Code Playgroud)
...创建一个新函数,在调用时,将使用this我们给出的值调用原始函数bind.
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |