Abdul Ahmad
Abdul Ahmad

Reputation: 10021

How to bind third party event to rxjs observable

I'm using a third party text editor called froala in a project and for the keyup event I have to pass a callback function so I can get the value back from the editor. I'm trying to wrap the callback function in an observable somehow so I can use debounceTime but I can't get it to work right, here's some code:

in my component file:

export class EditorComponent
  editorOptions = {
    events: {
      'froalaEditor.keyup': (e, editor) => {
        do stuff here
      },
    }
  };
}

I tried to use this for the keyup event but it's not working because it's setting up a new observable for each event:

'froalaEditor.keyup': (e, editor) => {
  const text = editor.html.get();
  Observable.create(o => {
    this.service.updateData(data);
  }).pipe(takeUntil(this.ngUnsubscribe))
    .pipe(debounceTime(1000))
    .subscribe();
}

what's the right way to make this work?

Upvotes: 1

Views: 182

Answers (1)

kos
kos

Reputation: 5364

You could create a standalone Subject and push values into it, like:

export class EditorComponent
  private onKeyup$ = new Subject();

  editorOptions = {
    events: {
      'froalaEditor.keyup': (e, editor) => {
        onKeyup$.next(e);
      },
    }
  };
}

Important: in this case you'll have to care about subscription completion by yourself. Search for proper observable completion in components for your particular framework.

OR

If you have a reference to the editor DOM node -- you could use fromEvent on froala event froalaEditor.keyup (see froala docs).

E.g.

const onKeyup$ = fromEvent(froalaDOMNode, 'froalaEditor.keyup');

In this case observable will complete once DOM node is destroyed, so you wont have to worry about unsubscribing manually.

Upvotes: 1

Related Questions