Aurelia自定义元素中的双向绑定无法正常工作

时间:2016-08-21 12:11:41

标签: javascript aurelia bootstrap-datepicker aurelia-binding

尝试学习Aurelia 1.0,我似乎无法在自定义元素上实现双向绑定。

使用bootstrap-datepicker我制作了一个日期范围选择器自定义元素:

日期范围-picker.js

import {bindable, bindingMode, inject} from 'aurelia-framework';
import $ from 'jquery';
import datepicker from 'bootstrap-datepicker';

@inject(Element)
export class DateRangePicker {
  @bindable startName = 'start';
  @bindable endName = 'end';
  @bindable startValue = null;
  @bindable endValue = null;

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

  attached() {
    $(this.element).find('.input-daterange').datepicker();
  }
}

日期范围-picker.html

<template>
  <div class="input-daterange input-group" id="datepicker">
    <input type="text" class="input-sm form-control" 
      name="${startName}" id="${startName}" 
      value.two-way="startValue" 
      placeholder="Start Date (mm/dd/yyy)" />
    <span class="input-group-addon">to</span>
    <input type="text" class="input-sm form-control" 
      name="${endName}" id="${endName}" 
      value.two-way="endValue" 
      placeholder="End Date (mm/dd/yyy)"/>
  </div>
</template>

自定义元素用于leads.html:

<div class="col-sm-12">
  <form role="form" class="form-inline" submit.delegate="search()">
    <div class="form-group">
      <date-range-picker 
        start-name="createdAtStartDate" start-value.two-way="startDate" 
        end-name="createdAtEndDate" end-value.two-way="endDate">  
      </date-range-picker>
    </div>
    <button type="submit" class="btn btn-primary">Search</button>
  </form>
</div>

leads.js

import {inject} from 'aurelia-framework';
import {LeadsService} from './leads-service';
import moment from 'moment';

@inject(LeadsService)
export class Leads {
  startDate = moment().format('M/D/YYYY');
  endDate = moment().format('M/D/YYYY');
  leads = [];

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

  search() {
    this.dataService.getLeads({
      startDate: this.startDate,
      endDate: this.endDate
    })
   .then(leads => this.leads = leads);
  }
}

日期范围选择器按预期工作,并且在lead.js中的startDate和endDate设置的任何值都正确绑定到自定义元素中的输入框但是当我提交表单时startDate和endDate甚至不会更改如果我改变输入框的值。

任何想法我做错了什么?

1 个答案:

答案 0 :(得分:2)

这些值正在通过javascript进行更新,因此您必须发送输入的更改事件,如下所示:

 attached() {
    $(this.element).find('.input-daterange').datepicker()
      .on('changeDate', e => {
        e.target.dispatchEvent(new Event('change'));
      });
  }

这是一个正在运行的示例Microsoft best pratice