Aurelia 自定义元素中的 2 种数据绑定方式 - 将自定义元素绑定到父视图模型

2 way databinding in Aurelia custom elements - bind custom element to parent viewmodel

在我的应用程序中,我做了很多 "services",我可以将它们注入到我的视图模型中,以节省一些冗余和时间。

现在我希望更进一步,将这些表单元素(select、文本、复选框 - 初学者的 select 下拉菜单)制作成自定义元素,仅在自定义元素中注入服务。

我可以让它在某种程度上发挥作用。当我在 "parent" 视图中需要它时,自定义元素(在本例中为 select)会显示,但是当我更改自定义 select 元素的 selected 值时,它不绑定到 "parent" 视图模型,这是我的要求。

我希望能够通过模板中的绑定属性将我的 selected 值从自定义元素绑定到 "parent" 视图模型上的 属性。

我会在几分钟内更新其中的一小段代码。

create.js(我称之为父视图模型)

import {bindable} from 'aurelia-framework';
export class Create{
    heading = 'Create';
    @bindable myCustomElementValue = 'initial value';
}

create.html(父视图)

<template>
    <require from="shared/my-custom-element"></require>
    <my-custom selectedValue.bind="myCustomElementValue"></my-custom>
    <p>The output of ${myCustomElementValue} should ideally be shown and changed here, as the select dropdown changes</p>
</template>

我的-custom.js

import { inject, bindable} from 'aurelia-framework';
import MyService from 'my-service';

@inject(MyService )
export class MyCustomCustomElement {
    @bindable selectedValue;

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

    selectedValueChanged(value) {
        alert(value);
        this.selectedValue = value;
    }

    async attached() {
        this.allSelectableValues = await this.myService.getAllValues();
    }
}

最初发生的是 create.html 视图输出 "initial value",当我更改自定义元素 select 的值时,新的 selected 值得到提醒out,但它不会更新绑定的父变量,它仍然只是显示 "initial value".

这里有几个问题:

  1. 由于不区分大小写

    ,DOM 中的任何 属性 名称都需要 kebab-case

    selected-value.bind="property"

    不是

    selectedValue.bind="property"

  2. 您需要双向绑定。使用装饰器创建 @bindable 时,其中一个参数是 BindingMode,用于设置默认绑定模式。

    Aurelia 设置了一些合理的默认值,例如input value.bind=".." 的默认值是两种方式而不是显式的

    如果您不想设置默认绑定模式,您可以直接使用绑定:

    selected-value.two-way="prop"

希望这对您有所帮助:)

编辑:我认为 API 在这个答案之后发生了一些变化。

@bindable 装饰器具有以下符号:

bindable({
  name:'myProperty',
  attribute:'my-property',
  changeHandler:'myPropertyChanged',
  defaultBindingMode: bindingMode.oneWay,
  defaultValue: undefined
})

检查快速参考的最佳位置之一是文档中的 Aurelia 作弊-sheet:

http://aurelia.io/docs/fundamentals/cheat-sheet