将模型属性绑定到自定义元素输入

时间:2017-09-19 07:38:51

标签: aurelia aurelia-binding

我试图将自定义元素输入数据绑定到父模型属性: 自定义元素的this.fieldValue应该最终绑定到容器\父页面的registration.firstName属性。 查看相关代码: 这是自定义元素HTML:

<template>
   <label>
       ${title}<input name.bind="fieldName" custom-type="text" 
                 title.bind="title" focusout.trigger="focusoutAction()" />                           
  </label>
</template>

这是视图模型(简化):

import {inject, bindable, customElement, bindingMode} from   
'aurelia-framework';

@customElement('form-input')
@inject(Element)
export class FormInputCustomElement {
@bindable({ defaultBindingMode: bindingMode.twoWay }) value;
@bindable title;
@bindable customType;
@bindable placeHolder;
@bindable fieldName;
@bindable onFocusout;



constructor(element) {
   this.element = element;
   this.input = null;
   this.fieldValue = '';
}

bind(bindingContext) {
  this.input = this.element.getElementsByTagName("input")[0];
  this.input.type = this.customType || "text";
  this.input.placeholder = this.placeHolder || "";
}

  focusoutAction() {
    this.fieldValue = this.input.value;
    this.onFocusout();
  }
}

在自定义元素中,我可以看到this.fieldValue获取输入文本。 这是容器相关代码:

<template>
<require from="./../../formControllers/formInput"></require>

  <div>
    ${fieldValue}<form-input name="firstName" id="firstName" field-
    value.bind="registration.firstName" title="First Name" 
    validate="registration.firstName" place-holder="Enter first name" field-
    name="firstName" on-focusout.call="validateInput()" />
</div>

<button type="button"  click.delegate="createNewAccount()">Create New 
 Account</button>

这是课程相关代码:

import { inject, bindable } from 'aurelia-framework';
export class AccountRegistration {

constructor() {
   this.initRegistration();
}

initRegistration() {
    this.registration = {};
    this.registration.firstName = '';
}

createNewAccount() {
var a = this.registration.firstName;
}

问题是,当我到达createNewAccount函数时, this.registration.firstName为空,尽管它绑定到自定义元素 field-value(camelCase中的fieldValue)属性,设置为自定义元素的输入文本。 我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

我认为问题是     @bindable({ defaultBindingMode: bindingMode.twoWay }) value;

这应该是@bindable({ defaultBindingMode: bindingMode.twoWay }) fieldValue;

同样在您的模板<input value.bind="fieldValue" />

现在,当您将registration.firstname绑定到表单中的field-value时,它将绑定到输入上的值。