带有Angular2的Redactor计数器插件

时间:2018-02-09 13:32:14

标签: angular typescript redactor redactor.js

我正在尝试使用Redactor添加一些插件。问题是计数器插件在页面加载后显示0个字和0个字符。

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

我尝试使用“init”回调来执行计数器插件的count()方法,如文档所示:

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

...此时一切似乎都没问题,VSCode中没有编译错误,但是在控制台中出现以下错误:

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)

我做错了什么?

谢谢,

2 个答案:

答案 0 :(得分:0)

this.counter中,this指的是init中的函数,而不是全局类。请改用箭头功能:

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

这仅适用于在编译器上下文之外引用组件类的counter

答案 1 :(得分:0)

最后我找到了解决方案:

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

不得不添加“插件”来引用插件我想要达到的目的。