Arturo Martinez Arturo Martinez - 2 months ago 9
TypeScript Question

creating new bindingContext to be used by children view models

I have 2 custom controls

parent-control
and
child-control
. I need child to execute functionalities on behalf of the parent. and the requirement is that child should be used within parent boundaries.

usage example

...<content-around> <!-- this is 'outerContext' bindingContext -->
<parent-control shared.bind="outerContext.something">
<div>
<child-control property="nameOfMemberOfShared"></child-control>
</div>
<div>
<span>some text here</span>
<child-control property="anotherNameOfMemberOfShared"></child-control>
</div>
</parent-control>
</content-around>...





parent-control.html

<template>
<slot></slot>
</template>





parent-control.ts (assuming all the imports)

export class ParentControlCustomElement {
@bindable shared: any;

bind(bindingContext, overrideContext) {
//here want to make sure elements rendered inside slot
//are able to access 'shared'
}
}





child-control.html

<template>
<!-- this is for simplicity more advanced stuff needed here -->
<h1>${sharedObject[property]}</h1>
</template>





child-control.ts (assuming all imports)

export class ChildControlCustomElement {
@bindable property: string;
sharedObject: any;

bind(bindingContext, overrideContext) {
this.sharedObject = bindingContext.shared;
// the problem is HERE!
// instead of getting a binding context pointing
// to parent-control view model I get binding context
// pointing to 'outerContext'
}
}


How can I make sure that starting at
parent-control
inner components will get a binding context pointing to
parent-control
's view model?

Answer

If you know your child control will always be used within the parent control you can declare a dependency on the ancestor/parent:

@inject(ParentControlCustomElement)
export class ChildControlCustomElement {
  constructor(parentControl) {
    this.parentControl = parentControl;
  }
}

If it you don't know for sure whether the child control will be used within the parent, use @inject(Optional.of(ParentControlCustomElement)).