I'm trying to modify a plugin I found for Redactor to get it working with the newest version, but my ignorance of JavaScript is keeping me from getting it working.
if (!RedactorPlugins) var RedactorPlugins = {};
RedactorPlugins.wordcount = function() {
return {
init: function() {
var self = this;
var $box = $(this.core.getBox());
if ($box.length>0) {
if ($box.find('.redactor-wordcount').length==0) {
var $wordcount_holder = $('#counter');
$box.on('keyup', function () {
$wordcount_holder.text('Words: ' + self.count());
});
$wordcount_holder.text('Words: ' + self.count());
}
}
},
count: function() {
var html = this.get(),
text = $(html).text().replace(/\t+/g, " ").replace(/\n/g, " ").replace(/\s+/g, " ");
return text.split(' ').length - 1;
}
};
};
When I load the page an error is output saying Uncaught TypeError: undefined is not a function
. It's referring to the count
function.
I was under the impression this syntax:
return {
...
}
Caused an object to be returned, but for some reason calling self.count()
causes the above error to be thrown.
How can I call the count
function from inside the init
function?
EDIT: AS an aside, here is how Redactor plugins (for the new version of the software) are supposed to be defined:
if (!RedactorPlugins) var RedactorPlugins = {};
RedactorPlugins.myplugin = function()
{
return {
myMethod: function()
{
// your code
}
};
};
I suspect that Redactor is calling init()
with this
pointing to some object that is different than what you expect. In order to call count()
, you probably need to declare it before your return
statement so you can use it in multiple places.
RedactorPlugins.wordcount = function() {
// Declare count here, then remove 'this.' when you call it (see my comments below)
var count = function() {
var html = this.get(),
text = $(html).text().replace(/\t+/g, " ").replace(/\n/g, " ").replace(/\s+/g, " ");
return text.split(' ').length - 1;
}
return {
init: function() {
var self = this;
var $box = $(this.core.getBox());
if ($box.length>0) {
if ($box.find('.redactor-wordcount').length==0) {
var $wordcount_holder = $('#counter');
$box.on('keyup', function () {
// Note the lack of 'this' here...
$wordcount_holder.text('Words: ' + count());
});
// ... and here
$wordcount_holder.text('Words: ' + count());
}
}
},
// Pass your count function as part of the return value
// if you still want it to be accessible to whoever uses
// the return value of this function.
count: count
};
};
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다