【问题标题】:creating new bindingContext to be used by children view models创建新的 bindingContext 供子视图模型使用
【发布时间】:2017-01-24 16:28:07
【问题描述】:

我有 2 个自定义控件 parent-controlchild-control。我需要孩子代表父母执行功能。并且要求是 child 应该在 parent 范围内使用。

使用示例

...<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(假设所有导入)

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(假设所有导入)

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'
  }
}

如何确保从parent-control 开始的内部组件将获得指向parent-control 的视图模型的绑定上下文?

【问题讨论】:

    标签: javascript typescript dependency-injection aurelia


    【解决方案1】:

    如果您知道您的子控件将始终在父控件中使用,您可以声明对祖先/父控件的依赖:

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

    如果您不确定子控件是否会在父控件中使用,请使用@inject(Optional.of(ParentControlCustomElement))

    【讨论】:

    • 有意思,我试试看
    猜你喜欢
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 2015-09-19
    相关资源
    最近更新 更多