Define socket io function outside of "on" statement - javascript

I'm writing code with Socket.io in JavaScript and I've been trying to define the function that happens during a certain event outside of the event statement because I want to reuse the function later. So instead of the usual:
socket.on('eventName',function(input){
//code triggered by event
});
I want to declare the function beforehand and then use it in the "on" statement:
function myFunction(input){
//some code
}
socket.on('input', myFunction(input));
So far I haven't had any success and I keep getting this error in Terminal:
nodejs exception: ReferenceError: input is not defined
in reference to the input being sent from the client with the 'input' event. Do I always have to define the code that happens when the event is triggered in the "on" statement?

What you want is to pass a reference to myFunction, like this:
socket.on('input', myFunction);
What you're doing with myFunction(input) is actually executing myFunction with an undefined variable input as its argument (hence the error).

Related

Event function declaration

Im trying to understand the declaration of the event handler and the function declaration in this post: https://stackoverflow.com/a/46418688/7727532
Im pretty new to Javascript and jQuery and trying to understand. What I do know is that you declare like the following
$('#clickMe').on('click', doSomeThing(e));
function doSomeThing(e){
console.log(e);
}
The first part I dont understand is
(e) => this._handleScaling(e)
What is happening here? We catch the current object and sending it to function _handleScaling()? But why do we have "(e) =>" before?
Second part is
_handleScaling(e) {
Which if Im right is a local function inside another? Because of the underline start. So maybe the code in the link isnt telling the whole picture?
You need to give function reference rather than function's return value
Replace
$('#clickMe').on('click', doSomeThing(e));
with
$('#clickMe').on('click', doSomeThing); //e is the event object will be automatically passed on to the event handler
The first part I dont understand is
(e) => this._handleScaling(e) What is happening here? We catch the
current object and sending it to function _handleScaling()? But why do
we have "(e) =>" before?
No, _handleScaling is only passed e (event object) so that it can get access to element on which this event has been triggered using e.target since with arrow function this will refer to scope in which this arrow function is defined.

how to create instances of a function in javascript?

Im trying to add an event listener to a object for example:
this.startLoading = function(){
this.a.addEventListener("complete", this.loadingHandler()); this gives me an error
},
this.loadingHandler = function(){
console.log("im doing something")
}
ERROR: "Uncaught Error: addListener only takes instances of
Function. The listener for event "complete" is "undefined"
However if I put the loadingHandler() function inside the scope it works, for example:
this.startLoading = function(){
var loadingHandler = function(){...}
this.a.addEventListener("complete", loadingHandler()); // this works
},
Im not sure what instances of a function means in that regard?
When you put () after a reference to a function, that means to call the function, and the value of the expression is whatever the function returns.
Your second example, that you say works, actually will not work, and you'll get the same error if the "startLoading" function is called.
Because you probably need to retain the proper context (this), what you probably need is
this.a.addEventListener("complete", this.loadingHandler.bind(this));
The .bind() method returns a function (exactly what addEventListener requires) that in turn will invoke your function such that this has the value requested.

Chrome not recognizing function arguments correctly

I have wrote some cross browser code for adding event listeners, then chrome started being funky, anyone know why this is happening?
Add Event listener code:
function addEventListener(Elm,Type,Func)
{
if(Elm.attachEvent)
Elm.attachEvent((Type.substr(0,2) == 'on' ? Type : 'on'+Type),Func);
else
Elm.addEventListener(Type,Func);
}
Code calling the method:
addEventListener(window,'load',SetSize);
addEventListener(window,'resize',SetSize);
Error:
Uncaught TypeError: Object load has no method 'addEventListener'
You can very clearly see that I have passed the arguments in the correct order yet they are not interpreted in said order..
You have overwritten window.addEventListener.
The native signature is: event_name, callback but yours is: object, event_name, callback.
Change the name of your function addEventListener or namespace it, like my_framework.addEventListener
You have redefined window.addEventListener. Anything you declare in the global namespace basically belongs to window, so:
function addEventListener(...) {
}
is the same as:
window.addEventListener = function(...) {
}
The argument signature for the native addEventListener is eventName, listener, but you have Elm, Type, Func.
Then inside your function body, you are doing Elm.addEventListener and passing it 'load' and SetSize. In that call, it calls your function again (because Elm is window) and this time, it attempts to call addEventListener on the string 'load', which won't work because a string doesn't have that method.
Change the name of your function, or namespace it, and it should work.
I would say the window object has not .attachEvent or .addEventListener.
This may caused because your function is named addEventListener and has overwritten the window.addEventListener()

parse data with event listener?

Is there a way to parse data to a function from the event listener ?
I have this:
div.addEventListener('mousedown',run(id),false);
function run(e,id){
console.log(id);
}
Thing is it executes straight away. The other problem is - if i want to parse the variable id, and the run function recieves e for the event, how do you parse any thing else =/ It's a bit confusing to work out what order e is (before or after your designated variables that you want to parse)
The current work around so far was to assign id to window so its basically a global... but i'm wondering if parsing via the event is possible at all ?
One way is to create a new listener function in which the id variable is already bound to the value that you want, like this:
function newListener(id) {
var listener = function(e) {
console.log(id);
}
return listener;
}
div.addEventListener('mousedown',newListener(id),false);
newListener(id) defines a new function, in which the value that the id variable had at the time is available inside that function. Then the javascript environment will call that function when the mouse button is pressed.
An event handler does not take arguments directly, you are calling the function run(id), not passing a handler, here is how you pass it (using anonymous function)
https://developer.mozilla.org/en/docs/DOM/element.addEventListener
div.addEventListener('mousedown',function(e){
doSomething(id);
},false);
function doSomething(id){
console.log(id);
}

jQuery: why does my live() handler declaration error out when the analogous click() one doesn't?

I have the following in a javascript file (using jQuery as well):
$(function(){
$('#mybutton').live('click',myObject.someMethod);
});
var myObject = {
someMethod: function() { //do stuff }
};
I get a js error on pageload that says "myObject isn't defined". However, when I change the event handler in the doc.ready function to:
$('#mybutton').live('click', function(){ myObject.someMethod(); });
it works! I have code structured like the first example all over my codebase that works. W T F??
In the first code block, you're trying to assign the value of myObject.someMethod (which is declared after this code block) to the second parameter for live().
When you wrap it in an anonymous function, as in the second block, the anonymous function doesn't get executed until the live event gets triggered. myObject.someMethod has been created by this point, so the code works as expected.
In the second case the lookup on myObject is deferred until the point at which the click handler is executed. In the first case, (in some cases, see below) the lookup must be immediate... as myObject is not yet defined, you get an error. Is there any reason not to add the event handler after myObject has been declared and assigned?
EDIT
As commented above, is it possible that this code is running after the .ready() event has fired.
jQuery docs say this about the .ready() method:
If .ready() is called after the DOM has been initialized, the new handler passed in will be executed immediately.
In this case, your ready handler will fire synchronously, thus requiring myObject to be defined.
Maybe the document.ready scope has another variable named myObject which hides the original one?

Categories