如何在Aurelia Js的with.bind属性中获取父对象

时间:2015-08-10 02:39:08

标签: html aurelia

我有以下ViewModel的构造函数:



export class ViewModel{
  data_1 = {id: 1, name: 'John'};
  currency = {id: 1, name: 'USA'};
}




在我的html中,我通过" with.bind"来绑定数据:



<div with.bind="data_1">
  <span textcontent.one-time="id"></span>
  <span textcontent.one-time="name"></span>
  <div with.bind="currency">
    <span text.content="name"></span>
  </div>
</div>
&#13;
&#13;
&#13;

当我想在data_1中绑定我的货币时,我遇到了问题,它无法识别货币。我怎样才能获得货币?

4 个答案:

答案 0 :(得分:3)

为什么不简化并摆脱with.bind?

<div>
    <span textcontent.one-time="data_1.id"></span>
    <span textcontent.one-time="data_1.name"></span>
    <div>
      <span textcontent.one-time="currency.name"></span>
    </div>
  </div>

答案 1 :(得分:0)

问题是with属性没有提供对$parent上下文的引用。我不确定这是处理它的最佳方式,但您可以创建自己的$parent自定义属性。

基于原始with

import {inject} from 'aurelia-dependency-injection';
import {BoundViewFactory, ViewSlot, customAttribute, bindable, templateController} from 'aurelia-templating';

@customAttribute('with-parent')
@templateController
@inject(BoundViewFactory, ViewSlot)
export class WithParent {

    constructor(viewFactory, viewSlot) {
        this.viewFactory = viewFactory;
        this.viewSlot = viewSlot;
    }

    bind(executionContext) {
        this.executionContext = executionContext;
        this.valueChanged(this.value);
    }

    valueChanged(newValue) {
        if (!this.view) {
            newValue.$parent = this.executionContext;
            this.view = this.viewFactory.create(newValue);
            this.viewSlot.add(this.view);
        }
        else {
            this.view.bind(newValue);
        }
    }
}

然后使用是透明的:

<div with-parent.bind="data_1">

    <span textcontent.one-time="id"></span>
    <span textcontent.one-time="name"></span>

    <div with-parent.bind="$parent.currency">

        <span textcontent.one-time="name"></span>

        <div with-parent.bind="$parent.$parent.another">
            <span textcontent.one-time="name"></span>
        </div>
    </div>
</div>

答案 2 :(得分:0)

使用$ parent和with.bind现在可以使用aurelia-framework@1.1.5

例如,以下内容将视图模型引用(bar)添加到父级而不是foo

<element with.bind="foo">
    <child-element view-model.ref="$parent.bar"></child-element>
</element>

答案 3 :(得分:-1)

$ parent为您提供对视图模型的引用,以便$ parent.currency