javascript - Pass action to a component with the parent's context in Aurelia -


how can pass action parent view/component child component , still maintain context of parent. problem shown in below plunkr shows if action executed in component in context of component , not parent passed action. typical "that = this" issue.

yes can use eventaggregator this, how without it. have pass whole viewmodel component?

http://plnkr.co/edit/n1xpudr5nhxwwiivawbj?p=preview

// app.js import { inject } 'aurelia-framework'; import { myservice } './my-service';  @inject(myservice) export class app {     constructor(myservice) {         this.myservice = myservice;         this.message = "hello world!";     }      dothing() {         console.log('do thing');         this.myservice.foo();     } }  <!--app.html--> <template>     <require from="./my-component"></require>     <p>${message}</p>     <button click.delegate="dothing()">do thing - in app.html</button>     <my-component do.bind="dothing"></my-component> </template>  // my-component.js import { bindable } 'aurelia-framework';  @bindable('do') export class mycomponentcustomelement {  }  <!-- my-component.html --> <template>     <button click.delegate="do()">do thing - in my-component</button> </template>  // my-service.js export class myservice {     foo() {         alert("pity da foo");     } } 

if wanted (there may cleaner ways go it), need access parent's view-model child view-model , then, when calling method in child view's click binding, use .call() change scope/context of do() method when it's called.

so in child view-model, first gain access parent's view-model adding following bind method:

bind( bindingcontext ) {     // bindingcontext parent view-model     this.parent = bindingcontext; } 

after have access parent view-model can update click binding in child view follows:

<button click.delegate="do.call( parent )">do thing - in my-component</button>

this call do() method parent view-model's context.

you can use either .call( scope/context, list, of, args, ... ) or .apply( scope/context, [array of args]). more info on .call() method check out mozilla's explanation


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -