0

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!

LStarky
  • 2,740
  • 1
  • 17
  • 47

1 Answers1

1

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

Community
  • 1
  • 1
Fabio
  • 11,892
  • 1
  • 25
  • 41
  • Thanks... that worked. Do you know if there's a way to do this from within the view's HTML markup (see original question)? – LStarky Feb 04 '17 at 23:46
  • I think you'd have to inject the parent and use it as a paremeter. Something like this `click.delegate="goButton.call(parent, { btn: btn })`. – Fabio Feb 05 '17 at 01:29