在Aurelia中将数据从一个视图模型传递到另一个视图模型

Jor*_*dec 6 ecmascript-6 aurelia aurelia-binding

我有一个名为的页面entry-main,它包含以下模板:

<template>
    <entry-search></entry-search>
    <entry-details></entry-details>
</template>
Run Code Online (Sandbox Code Playgroud)

里面<entry-search>有另一个自定义元素.它看起来像这样:

<template>
    <div class="row">
        <div class="col-lg-12">
            <div class="input-group">
                <span id="entry_search" class="input-group-addon">
                    <span class="fa fa-search"></span>
                </span>
                <!-- important part -->
                    <typeahead id="choose" placeholder="Holding the place"></typeahead>
                <!-- end of important part -->
            </div>
        </div>
    </div>
</template>
Run Code Online (Sandbox Code Playgroud)

在typeahead viewmodel中,我得到了我的typeahead的值,如下所示:

$(this.id).on('typeahead:selected', function (e, item) {
       this.selected = item;
});
Run Code Online (Sandbox Code Playgroud)

我现在的问题是,如何this.selected从我的entry-details-viewmodel中获取我的typeahead-viewmodel?
为了清楚起见,它应该是这样的:

<entry-main>
    <entry-search>
          <typeahead></typeahead>
    </entry-search>

    <entry-details>
          ${selected}
    </entry-details>
</entry-main>
Run Code Online (Sandbox Code Playgroud)

Fab*_*Luz 5

你可以这样做:

在以下位置创建"已选中"属性entry-main:

export class EntryMain {
    selected = '';
    //rest of the code
}
Run Code Online (Sandbox Code Playgroud)

在以下位置创建可绑定属性typeahead:

import { bindable } from 'aurelia-framework';

export class Typeahead {
    @bindable selected;
    //... rest of the code
}
Run Code Online (Sandbox Code Playgroud)

将typeahead的"selected"绑定到entry-main的"selected"

<entry-main>
    <entry-search>
        <typeahead selected.bind="selected"></typeahead>
    </entry-search>

    <entry-details>
        ${selected}
    </entry-details>
</entry-main>
Run Code Online (Sandbox Code Playgroud)

未经测试的代码,但我认为它应该有效.

  • 这实际上可行.我自己没有测试过,但是我使用了Aurelia的`EventAggregator`.这样我就可以轻松地将数据从任何视图模型传递到任何其他随机视图模型. (3认同)