Как запустить метод объекта onEvent в JavaScript?

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

Итак, скрипт, который я пытаюсь запустить, предполагает подсчет символов в текстовом поле и обновление абзаца, чтобы сообщить пользователю, сколько символов они набрали. У меня есть объект с именем charCounter. sourceId - это идентификатор текстовой области для подсчета символов. statusId - это идентификатор абзаца, который нужно обновлять при каждом нажатии клавиши.

function charCounter(sourceId, statusId) {
    this.sourceId = sourceId;
    this.statusId = statusId;
    this.count = 0;
}

Существует один метод с именем updateAll. Он обновляет количество символов и обновляет абзац.

charCounter.prototype.updateAll = function() {
    //get the character count;
    //change the paragraph;
}

У меня есть функция запуска, которая вызывается при загрузке окна.

function start() {
    //This is the problem
    document.getElementbyId('mytextfield').onkeydown = myCounter.updateAll;
    document.getElementbyId('mytextfield').onkeyup = myCounter.updateAll;
}

myCounter = new charCounter("mytextfield","charcount");
window.onload = start;

Приведенный выше код является проблемой. Почему в мире я не могу вызвать метод myCounter.updateAll при возникновении события? Это действительно смущает меня. Я понимаю, что если вы вызываете методнравится() вы получите значение из функции. Если вы называете этонравится вы получаете указатель на функцию. Я указываю свое событие на функцию. Я также попытался вызвать функцию прямо вверх, и она работает просто отлично, но она не будет работать, когда происходит событие.

Чего мне не хватает?

Спасибо за ответы на все вопросы. Вот три разных реализации.

Реализация 1
function CharCounter(sourceId, statusId) {
    this.sourceId = sourceId;
    this.statusId = statusId;
    this.count = 0;
};
    CharCounter.prototype.updateAll = function() {
        this.count = document.getElementById(this.sourceId).value.length;
        document.getElementById(this.statusId).innerHTML = "There are "+this.count+" charactors";
    };

function start() {
    myCharCounter.updateAll();
    document.getElementById('mytextfield').onkeyup = function() { myCharCounter.updateAll(); };
    document.getElementById('mytextfield').onkeydown = function() { myCharCounter.updateAll(); };   
};

myCharCounter = new CharCounter('mytextfield','charcount');
window.onload = start;
Реализация 2
function CharCounter(sourceId, statusId) {
    this.sourceId = sourceId;
    this.statusId = statusId;
    this.count = 0;
};
    CharCounter.prototype.updateAll = function() {
        this.count = document.getElementById(this.sourceId).value.length;
        document.getElementById(this.statusId).innerHTML = "There are "+ this.count+" charactors";
    };
    CharCounter.prototype.start = function() {
        var instance = this;
        instance.updateAll();

        document.getElementById(this.sourceId).onkeyup = function() {
            instance.updateAll();
        };
        document.getElementById(this.sourceId).onkeydown = function() {
            instance.updateAll();
        };
    };

window.onload = function() {
    var myCounter = new CharCounter("mytextfield","charcount");
    myCounter.start();
};
Реализация 3
function CharCounter(sourceId, statusId) {
    this.sourceId = sourceId;
    this.statusId = statusId;
    this.count = 0;
};
    CharCounter.prototype.updateAll = function() {
        this.count = document.getElementById(this.sourceId).value.length;
        document.getElementById(this.statusId).innerHTML = "There are "+this.count+" charactors";
    };

function bind(funcToCall, desiredThisValue) {
    r,eturn function() { funcToCall.apply(desiredThisValue); };
};  

function start() {
    myCharCounter.updateAll();
    document.getElementById('mytextfield').onkeyup = bind(myCharCounter.updateAll,    myCharCounter);
    document.getElementById('mytextfield').onkeydown = bind(myCharCounter.updateAll, myCharCounter);
};

myCharCounter = new CharCounter('mytextfield','charcount');
window.onload = start;

Ответы на вопрос(5)

Ваш ответ на вопрос