Redactor counter plugin with Angular2

177 views Asked by At

I am trying to use Redactor with some added plugins. The problem is that counter plugin shows 0 words and 0 characters after the page loaded.

{
  words: 0, 
  characters: 0, 
  spaces: 0
}

I've tried to use "init" callback to execute count() method of the counter plugin as the documentation shows:

$('#content').redactor({
  plugins: ['counter'],
  callbacks: {
    init: function()
    {
        this.counter.count();
    },
    counter: function(data)
    {
        console.log(data);
    }
  }
});

...at this point everything seems to be ok, there is no compile errors in VSCode, but I get the following error in console:

declare const $R: any;
...
...
$R('#editor', {
  plugins: [
    'counter',
    ...
  ],
  callbacks: {
    init: function() {
      this.counter.count();
    }
    counter: function(data: any) {
      console.log(data);
    }
  }
});

ERROR TypeError: Cannot read property 'count' of undefined
at App.changed (editor.component.ts:55)
at F._loop (scripts.bundle.js:2741)
at F.trigger (scripts.bundle.js:2711)
at App.broadcast (scripts.bundle.js:2185)
at F._syncing (scripts.bundle.js:10344)
at scripts.bundle.js:10316
at ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:4724)
at ZoneDelegate.invokeTask (zone.js:420)
at Zone.runTask (zone.js:188)

What am I doing wrong?

Thanks,

2

There are 2 answers

1
wilsonhobbs On

In this.counter, this refers to the function in init, not the global class. Use an arrow function instead:

callbacks: {
    init: () => {
      this.counter.count();
    }
    counter: (data: any) => {
      console.log(data);
    }
  }

this only applies if your referencing a counter on your component class, outside of the redactor context.

0
standby954 On

Finally I've found the solution:

declare const $R: any;
...
...
$R('#editor', {
  plugins: [
    'counter',
    ...
  ],
  callbacks: {
    syncing: function(html: any) {
      this.plugin.counter.count();
    },
    counter: function(data: any) {
      console.log(data);
    }
  }
});

Had to add "plugin" to refer the plugin what I wanted to reach.