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. However, it appears that the scope/context of the function is wrong (it's not seeing or updating the parent's 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. If it were a bound parameter, I think I could use action.call="onNew" but not in an array of objects. Help!


That's how javascript works. To solve this you can use:

{icon: 'fa-plus', display: 'New', action: this.onNew.bind(this) }

Running example: https://gist.run/?id=cefe45c5a402c348d01d41d9cde42489

Explanation:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

Javascript call() & apply() vs bind()?

https://alexperry.io/personal/2016/04/03/How-to-use-apply-bind-and-call.html

链接地址: http://www.djcxy.com/p/97008.html

上一篇: 这似乎是一个Javascript事件的类。 它是什么?

下一篇: Aurelia绑定按钮回调函数