绑定模板

时间:2016-09-22 12:53:28

标签: aurelia aurelia-binding

在app.html我正在绘制面包屑 面包屑模板

<template>
  <nav>
    <ol class="breadcrumb">
      <li repeat.for="crumb of breadcrumb" class="breadcrumb-item ${$last ? 'active' : ''}">
        ${crumb.name}
      </li>
    </ol>
  </nav>
</template>

现在,我想为每个页面的“breadcrumb”属性定义一个不同的值。但我更喜欢在app.html上调用面包屑模板一次。

export class PageA {
  breadcrumb = ['parentA', 'childA']
  constructor () {
  }
}

export class PageB {
  breadcrumb = ['parentB', 'childB']
  constructor () {
  }
}

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

如果要在app.html视图中声明breadcrumb自定义元素(而不是在每个单独的页面视图中)并将其breadcrumb属性绑定到子页面中声明的值,则最直接的解决方案是使用单独的单件服务,用于保存面包屑数据。

例如:

import { singleton } from "aurelia-framework";

@singleton()
export class BreadcrumbService {
    breadcrumb = [];
}

将它注入breadcrumb.js,如下所示:

import { inject } from "aurelia-framework"
import { BreadcrumbService } from "./breadcrumb-service";

@inject(BreadcrumbService)
export class Breadcrumb{
    constructor(breadcrumbService) {
        this.breadcrumbService = breadcrumbService;
    }
}

稍微修改了breadcrumb.html:

<template>
    <nav>
        <ol class="breadcrumb">
            <li repeat.for="crumb of breadcrumbService.breadcrumb" class="breadcrumb-item ${$last ? 'active' : ''}">
                ${crumb.name}
            </li>
        </ol>
    </nav>
</template>

然后在每个子页面中,您将注入BreadcrumbService并修改其breadcrumb属性,该属性会自动更新breadcrumb.js中的值:

import { inject } from "aurelia-framework"
import { BreadcrumbService } from "breadcrumb-service";

@inject(BreadcrumbService)
export class PageA {
    constructor(breadcrumbService) {
        breadcrumbService.breadcrumb = ['parentA', 'childA'];
    }
}

@inject(BreadcrumbService)
export class PageB {
    constructor() {
        breadcrumbService.breadcrumb = ['parentB', 'childB'];
    }
}

修改

你可能不得不强制对repeat.for进行绑定刷新,每次在breadcrumb服务上拼接breadcrumb数组,然后在你的子页面中更改它,当你将数组设置为不同的值时,目标绑定可能不会更新。这是因为repeat.for使用一个侦听.splice()等的集合观察器,但不检查数组对象引用是否相等。

您可以将其封装在BreadcrumbService:

import { singleton, TaskQueue, inject } from "aurelia-framework";

@singleton()
@inject(TaskQueue)
export class BreadcrumbService {
    breadcrumb = [];

    constructor(taskQueue) {
        this.taskQueue = taskQueue;
    }

    setBreadcrumb(breadcrumb) {
        this.breadcrumb.splice(0);

        // Using a micro task gives the repeat.for an opportunity to respond to the .slice() before setting the new values
        this.taskQueue.queueMicroTask(() => {
            this.breadcrumb.push(breadcrumb);
        });
    }
}

在您的子页面中:

import { inject } from "aurelia-framework"
import { BreadcrumbService } from "breadcrumb-service";

@inject(BreadcrumbService)
export class PageA {
    constructor(breadcrumbService) {
        breadcrumbService.setBreadcrumb(['parentA', 'childA']);
    }
}

@inject(BreadcrumbService)
export class PageB {
    constructor() {
        breadcrumbService.setBreadcrumb(['parentB', 'childB']);
    }
}