在指令angular2中设置回调函数

时间:2015-10-25 21:08:23

标签: callback directive angular

我尝试使用angular2中的componente作为指令。这是代码指令:

export class Datepicker {
    public date : Date;
    public callback : Function;

    constructor() {
        $('.datepicker').datepicker({
            dateFormat: 'dd/mm/yy',
            dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'],
            dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
            dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
            monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
            monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
            nextText: 'Próximo',
            prevText: 'Anterior',
            showOn: 'button',
            buttonImage: 'http://jqueryui.com/resources/demos/datepicker/images/calendar.gif',
            buttonImageOnly: true,
            onSelect: function(selectedDate) {
                console.log(this.callback);
            }
        });
    }

    setCallback(fn : Function){
        this.callback = fn;
    }
}

在html中:

<input class="mdl-textfield__input datepicker" [(ng-model)]="datepicker1" type="text"/>

在我的组件中使用此代码:

import {Component, NgIf, FORM_DIRECTIVES, ElementRef} from 'angular2/angular2';
import {Datepicker} from '../datepicker/datepicker';

declare function initMaterial();

@Component({
    selector: 'modal',
    directives: [NgIf, Datepicker, FORM_DIRECTIVES],
    templateUrl: './frontend/components/modal/modal.html',
    styleUrls: ['./frontend/components/modal/modal.css'],
    bindings: [Datepicker]
})

export class Modal {
    public isOpen : boolean = false;
    private dtCompromise : Date;
    private dsCompromise : String;
    private datepicker : Datepicker;

    constructor(datepicker : Datepicker){
        this.datepicker = datepicker;
        this.datepicker.setCallback(function(selectedDate : Date){
            console.log('Date: ' + selectedDate);
        });
    }
}

在html中:

<form action="#">
    <div class="mdl-textfield mdl-js-textfield">
        <datepicker callback="selectDate" [(ng-model)]="datepicker"/>
        <label class="mdl-textfield__label" for="dtCompromisse">Data</label>
    </div><br>
    <div class="mdl-textfield mdl-js-textfield">
        <textarea class="mdl-textfield__input" type="text" rows= "5" [(ng-model)]="dsCompromise"></textarea>
        <label class="mdl-textfield__label" for="dsCompromisse">Descrição</label>
    </div>
</form>

当调用选定的日期函数onSelect并且console.log打印未定义

onSelect: function(selectedDate) {
   console.log(this.callback);
}

什么是我的错误?

1 个答案:

答案 0 :(得分:0)

我。使用ViewChild指定具体的datepicker元素,然后在afterViewInit生命周期方法中指定setCallback

import {Component, ViewChild} from 'angular2/angular2';

@Component({
  selector: 'datepicker'
  // ...
})
export class Datepicker {
  // ...
}

@Component({
  selector: 'modal',
  directives: [NgIf, Datepicker, FORM_DIRECTIVES],
  // ...
})
export class Modal {
  //...
  @ViewChild('dp') datepicker : Datepicker;

  afterViewInit() {
    this.datepicker.setCallback(function(selectedDate : Date){
      console.log('Date: ' + selectedDate);
    });
  }
}

和模板是:

<form action="#">
    // ...
    <datepicker #dp callback="selectDate" [(ng-model)]="datepicker"/>
    // ...
</form>
this函数内的

II。 onSelect并未引用datepicker对象。要修复它,您有三个选择:

  1. 使用bind方法更改函数执行的上下文:
  2. export class Datepicker {
      // ...
      constructor() {
        $('.datepicker').datepicker({
          // ...
          onSelect: function(selectedDate) {
            console.log(this.callback);
          }.bind(this)
        });
      }
    }
    
    1. var self = this回调之外初始化onSelect,然后在其中使用self
    2. export class Datepicker {
        // ...
        constructor() {
          var self = this;
          $('.datepicker').datepicker({
            // ...
            onSelect: function(selectedDate) {
              console.log(self.callback);
            }
          });
        }
      }
      
      1. 如果您正在使用ES6,请使用arrow functions
      2. export class Datepicker {
          // ...
          constructor() {
            $('.datepicker').datepicker({
              // ...
              onSelect: (selectedDate) => {
                console.log(this.callback);
              }
            });
          }
        }