Hello!

There is a javascript code in OOP "style". The this.callbacks object contains functions that must be called when events in the eventHandler object eventHandler .

Suppose the user enters a value into input and the keyup event keyup , which calls the getMatches function.

The problem is that the Plugin function is called only once when the page is loaded and returns nothing, as a result of which, later on, the events ( keyup , focus ) do not work.

It is necessary to somehow inject this code into the page so that it is processed (invoked) always, as in a functional style.

JS Code:

 $(document).ready(function () { Plugin(); //Вызывается 1 раз, при загрузке документа }); var Plugin = function () { var self = this; this.callbacks = { findCities: { City: function (id, city) { //Do something... }, getMatches: function (input) { //Do something... } }, eventHandler: { keyup: function () { $('example-div').keyup(function (e) { // не срабатывает self.callbacks.findCities.getMatches(this); }) }, focus: function () { $('example-div').focus(function (e) { // не срабатывает var city = new self.callbacks.findCities.City(0, 'Moscow'); }); } } }; 

I could write this code in the usual functional "style".

Something like this (and it will work):

 $(document).ready(function () { $('example-div').keyup(function (e) { getMatches(this); }); $('example-div').focus(function (e) { var city = new City(0, 'Moscow'); }); }); function City(id, city) { //Do something... } function getMatches(input) { //Do something... } 
  • in my opinion there is no OOP at all. - Mikhail Vaysman
  • one
    oh wei ... wrong Plugin call In this case, Plugin is not a function, but a constructor . For hanging you need to call eventHandler.keyup () , etc. - Grundy
  • Thanks for the amendment. Indeed, I was mistaken in that Plugin is a constructor, not a function. But that's not the point. I need to understand how to implement the constant processing of the function when the page loads. That is, I called it once, and it handles events (this is similar to how jquery plugins work). - Alexander Sinitsyn
  • this.callbacks.eventHandler.keyup(); - You were answered: by calling this.callbacks.eventHandler.keyup(); at the end Plugin - Igor

1 answer 1

Something like this (but it’s not clear what the OOP is about):

 $(document).ready(function () { Plugin(); //Вызывается 1 раз, при загрузке документа }); function Plugin() { var callbacks = { findCities: { City: function (id, city) { //Do something... }, getMatches: function (input) { //Do something... } } }; $('example-div').keyup(function (e) { // не срабатывает callbacks.findCities.getMatches(this); }); $('example-div').focus(function (e) { // не срабатывает var city = new callbacks.findCities.City(0, 'Moscow'); }); };