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

Dac*_*d3r 10 aurelia aurelia-binding

在我的应用程序中,我已经制作了很多"服务",我可以在我的视图模型中注入,以节省som冗余和时间.

现在,我希望更进一步,并制作那些表单元素(选择,文本,复选框 - 启动器的选择下拉列表)并将它们转换为自定义元素,仅在自定义元素中注入服务.

我可以在某种程度上使它工作.我在"父"视图中需要时显示自定义元素(在这种情况下选择),但是当我更改自定义选择元素的选定值时,它不会绑定到"父"视图模型,这是我的要求.

我希望能够通过其模板中的bind属性将我选择的值从自定义元素绑定到"父"视图模型上的属性.

我会在几分钟内更新一个小代码片段.

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

import {bindable} from 'aurelia-framework';
export class Create{
    heading = 'Create';
    @bindable myCustomElementValue = 'initial value';
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

我-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();
    }
}
Run Code Online (Sandbox Code Playgroud)

最初的事情是create.html视图输出"初始值",当我更改自定义元素选择的值时,新选择的值会被警告,但它不会更新绑定的父变量,它仍然只显示"初始值".

Cha*_*leh 27

这里有几个问题:

  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
})
Run Code Online (Sandbox Code Playgroud)

检查快速参考的最佳位置之一是文档中的Aurelia备忘单:

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

  • 您应该将默认绑定模式设置为其他人(或您自己)期望的模式.我会说在这个例子中默认将它设置为双向,因为它是你控件中最自然的用法 - 你几乎总是希望`selected-value`双向绑定.这是Aurelia使用约定的方式,它运作良好. (3认同)