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

时间:2015-12-22 13:22:07

标签: ecmascript-6 aurelia aurelia-binding

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

<template>
    <entry-search></entry-search>
    <entry-details></entry-details>
</template>

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

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

$(this.id).on('typeahead:selected', function (e, item) {
       this.selected = item;
});

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

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

    <entry-details>
          ${selected}
    </entry-details>
</entry-main>

2 个答案:

答案 0 :(得分:5)

你可以这样做:

entry-main中创建“已选中”属性:

export class EntryMain {
    selected = '';
    //rest of the code
}

typeahead中创建一个可绑定属性:

import { bindable } from 'aurelia-framework';

export class Typeahead {
    @bindable selected;
    //... rest of the code
}

将typeahead的“selected”绑定到entry-main的“selected”

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

    <entry-details>
        ${selected}
    </entry-details>
</entry-main>

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

答案 1 :(得分:0)

正如@JorisDecraecker所说,可以使用EventAggregator完成。可以根据您的需要修改的示例代码:

app.html

<template>
   <button click.delegate = "publish()">PUBLISH</button><br/>
   <button click.delegate = "subscribe()">SUBSCRIBE</button><br/>
   <button click.delegate = "dispose()">DISPOSE</button>
</template>

app.js

import {inject} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator';

@inject(EventAggregator)
export class App {
   constructor(eventAggregator) {
      this.eventAggregator = eventAggregator;
   }

   publish() {
      var payload = 'This is some data...';
      this.eventAggregator.publish('myEventName', payload);
   }

   subscribe() {
      this.subscriber = this.eventAggregator.subscribe('myEventName', payload => {
         console.log(payload);
      });
   }

   dispose() {
      this.subscriber.dispose();
      console.log('Disposed!!!');
   }
}

来源:

https://www.tutorialspoint.com/aurelia/aurelia_event_aggregator.htm

相关问题