[英]Aurelia binding for button callback function
I want to pass an array of objects that define buttons to a custom element, like this: 我想将定义按钮的对象数组传递给自定义元素,如下所示:
<my-panel header="My Title"
view-buttons.bind="[{icon: 'fa-plus', display: 'New', action: onNew}]">
</my-panel>
In my custom element, I'm displaying the buttons like this: 在我的自定义元素中,我正在显示如下按钮:
<button repeat.for="btn of viewButtons" class="btn btn-default" click.delegate="goButton(btn)">
<i class="fa ${btn.icon} fa-fw"></i> ${btn.display}
</button>
The called function in my custom element's view-model is: 我的自定义元素的视图模型中的调用函数为:
goButton(btn) {
if (btn.action) {
btn.action();
}
}
The called function in my parent view-model is: 我的父视图模型中的调用函数是:
onNew() {
window.alert("HORRAY!!! Now why is this not working?");
console.log("view=", this.view); // should be 'home', but displays 'undefined'
this.view = 'new_view';
}
The button displays correctly and I get the window.alert
message which means the parent function was called. 该按钮正确显示,并且我收到window.alert
消息,这意味着已调用父函数。 However, it appears that the scope/context of the function is wrong (it's not seeing or updating the parent's this.view
). 但是,看来函数的作用域/上下文是错误的(它没有看到或更新父级的this.view
)。
What am I doing wrong? 我究竟做错了什么? My guess is that it's related to action: onNew
but I don't know how to fix it. 我的猜测是它与action: onNew
有关action: onNew
但我不知道如何解决。 If it were a bound parameter, I think I could use action.call="onNew"
but not in an array of objects. 如果它是一个绑定参数,我想我可以使用action.call="onNew"
但不能在对象数组中使用。 Help! 救命!
That's how javascript works. 这就是javascript的工作方式。 To solve this you can use: 要解决这个问题,您可以使用:
{icon: 'fa-plus', display: 'New', action: this.onNew.bind(this) }
Running example: https://gist.run/?id=cefe45c5a402c348d01d41d9cde42489 运行示例: https : //gist.run/?id = cefe45c5a402c348d01d41d9cde42489
Explanation: 说明:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
Javascript call() & apply() vs bind()? JavaScript call()和apply()与bind()?
https://alexperry.io/personal/2016/04/03/How-to-use-apply-bind-and-call.html https://alexperry.io/personal/2016/04/03/How-to-use-apply-bind-and-call.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.