Как вызвать метод внутри объекта?

Я пытаюсь изменить плагин, который я нашел для Redactor, чтобы заставить его работать с самой новой версией, но мое незнание JavaScript мешает мне заставить его работать.

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;
        }
    };
};

При загрузке страницы выдает ошибку Uncaught TypeError: undefined is not a function. Это относится к функции count.

Я был под впечатлением этого синтаксиса:

return {
...
}

Вызывает возврат объекта, но по какой-то причине вызов self.count() вызывает указанную выше ошибку.

Как я могу вызвать функцию count из функции init?

РЕДАКТИРОВАТЬ: В стороне, вот как должны быть определены плагины Redactor (для новой версии программного обеспечения):

if (!RedactorPlugins) var RedactorPlugins = {};

RedactorPlugins.myplugin = function()
{
    return {
        myMethod: function()
        {
            // your code
        }
    };
};

person Nate    schedule 18.12.2014    source источник
comment
В целом этот код должен работать: jsfiddle.net/La197r68 Похоже, вы пропустили что-то важное   -  person zerkms    schedule 18.12.2014
comment
Что такое this, когда вы звоните init()? Вы используете this.core и this.get(), но я нигде не вижу определения core или get().   -  person AJ Richardson    schedule 18.12.2014
comment
@aj_r Я не уверен. Это, вероятно, специфично для Redactor. Я удалю теги javascript и jquery.   -  person Nate    schedule 18.12.2014


Ответы (1)


Я подозреваю, что Redactor вызывает init(), а this указывает на какой-то объект, который отличается от того, что вы ожидаете. Чтобы вызвать count(), вам, вероятно, потребуется объявить его перед оператором return, чтобы вы могли использовать его в нескольких местах.

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
    };
};
person AJ Richardson    schedule 18.12.2014