Aurelia - 视图模型在哪个视图端口中呈现?

Aurelia - which view port is the view-model being rendered in?

我有一个双列布局设置,这两列的功能非常相似,因此重复使用了相同的视图模型。然而,渲染可能会略有不同,具体取决于渲染的哪一侧,所以想知道如何访问视口信息?

考虑这个设置:

app.js

export class App {
    configureRouter(config: RouterConfig, router: Router): void {
        config.map([ {
            route: '',
            name: 'home',
            viewPorts: {
                left: { moduleId: 'module1' },
                right: { moduleId: 'module1' },
            }
        }]);
    }
}

app.html

<template>
    <router-view name="left"></router-view>
    <router-view name="right"></router-view>
</template>

module1.js

export class Module1 {
    activate(params: Object, routeConfig: Object, instruction: NavigationInstruction): void {
        //which view port am I being rendered in?
    }
}

我的解决方案是查找导航指令的视口指令对象并比较它是否是完全相同的对象实例。为此,我创建了一个方便的方法。

navigation-instruction-extension.js

import {NavigationInstruction} from 'aurelia-router';

NavigationInstruction.prototype.viewPortFor = function(viewModelInstance: Object): string {
    for (let key in this.viewPortInstructions) {
        let vpi = this.viewPortInstructions[key];
        if (vpi.component.viewModel === viewModelInstance)
            return key;
    }
    return undefined;
}

module1.js

import 'navigation-instruction-extension.js';

export class Module1 {
    activate(params: Object, routeConfig: Object, instruction: NavigationInstruction): void {
        instruction.viewPortFor(this); //returns either 'left' or 'right'
    }
}

我添加了一个新的 Pull Request,当发布新版本时,将可以通过常规生命周期参数访问视口的名称:

activate(params: Object, routeConfig: Object, instruction: NavigationInstruction): void {
    routeConfig.currentViewPort //the name of current viewport
}