diff --git a/medium-editor.directive.ts b/medium-editor.directive.ts index 25285d4..aedf8de 100644 --- a/medium-editor.directive.ts +++ b/medium-editor.directive.ts @@ -1,3 +1,7 @@ +import 'rxjs/add/operator/debounceTime'; +import 'rxjs/add/operator/distinctUntilChanged'; +import 'rxjs/add/operator/takeUntil'; +import {Subject} from "rxjs/Subject"; import { Directive, ElementRef, @@ -19,7 +23,8 @@ import * as MediumEditor from 'medium-editor'; * + * [editorPlaceholder]="placeholderVar" + * [debounce]="5000"> */ @Directive({ selector: 'medium-editor' @@ -30,10 +35,13 @@ export class MediumEditorDirective implements OnInit, OnChanges, OnDestroy { private element: HTMLElement; private editor: any; private active: boolean; - + private inputEdited: EventEmitter = new EventEmitter(); + private componentDestroyed$: Subject = new Subject(); + @Input('editorModel') model: any; @Input('editorOptions') options: any; @Input('editorPlaceholder') placeholder: string; + @Input('debounce') debounce: number; @Output('editorModelChange') update = new EventEmitter(); @@ -41,8 +49,9 @@ export class MediumEditorDirective implements OnInit, OnChanges, OnDestroy { ngOnInit() { this.element = this.el.nativeElement; - this.element.innerHTML = '
' + this.model + '
'; + this.element.innerHTML = '
' + (this.model == undefined ? '': this.model) + '
'; this.active = true; + if (this.placeholder && this.placeholder.length) { this.options.placeholder = { @@ -53,8 +62,29 @@ export class MediumEditorDirective implements OnInit, OnChanges, OnDestroy { // Global MediumEditor this.editor = new MediumEditor('.me-editable', this.options); this.editor.subscribe('editableInput', (event, editable) => { - this.updateModel(); + let value = this.editor.getContent(); + value = value.replace(/ /g, '').trim(); + if(this.debounce != undefined){ + this.inputEdited.emit(value); + } + else{ + this.updateModel(value); + } }); + this.editor.subscribe('blur',()=>{ + if(this.debounce == undefined){return;} + let value = this.editor.getContent(); + value = value.replace(/ /g, '').trim(); + this.updateModel(value); + }) + + if(this.debounce != undefined){ + this.inputEdited + .takeUntil(this.componentDestroyed$) + .distinctUntilChanged() + .debounceTime(this.debounce) + .subscribe(x=> this.updateModel(x)); + } } refreshView() { @@ -73,9 +103,7 @@ export class MediumEditorDirective implements OnInit, OnChanges, OnDestroy { /** * Emit updated model */ - updateModel(): void { - let value = this.editor.getContent(); - value = value.replace(/ /g, '').trim(); + updateModel(value:string): void { this.lastViewModel = value; this.update.emit(value); } @@ -85,6 +113,8 @@ export class MediumEditorDirective implements OnInit, OnChanges, OnDestroy { */ ngOnDestroy(): void { this.editor.destroy(); + this.componentDestroyed$.next(true); + this.componentDestroyed$.complete(); } isPropertyUpdated(changes, viewModel) {