JQuery callback - severe violation

I get the basic idea of this , not in method , when in strict mode sketched here , but it gets a little erudite to be honest. So, in more prosaic terms:

I have a handler like this:

 $('.myClass').one('keyup', function() { var $this = $(this); etc etc }); 

I want to change it to this:

 function myFunction () { var $this = $(this); etc etc }; $('.myClass1').one('keyup', myFunction); $('.myClass2').one('keyup', myFunction); etc 

I do not like this because in strict mode , because I use this outside the method. I understand.

However, I need to have myFunction separate from the handler, because (1) it is attached to different classes / elements and (2) I use .off().one('keyup', myFunction) to reset the one handler for different classes at different points .

So, how do I get around using a separate callback function without breaking this business?

+6
source share
4 answers

I get a basic idea of ​​this not in the method, when in strict mode ...

Yes, but you mix two unrelated things: strict mode and JSLint. They are largely unrelated (except that JSLint has the ability to require strict mode).

There is no problem with your code in strict mode. This is completely correct and appropriate (due to the way jQuery uses this ). Example There is no “severe violation”.

JSLint does not like it, but JSLint does not like a lot of things that are absolutely correct and suitable. JSLint discovers a combination of things that are very widely recognized as problems (like missing semicolons) and things that Douglas Crockford doesn't like in terms of style. Crockford is smart and well-informed, but not everyone agrees with his choice of style.

Lint tools are very useful, which is an important part of the toolkit. JSLint is less useful than it can be (in my opinion) by combining issues with style elements (although it provided a thin line with JavaScript). You might consider using JSHint , which gives you more control over what it checks.

+6
source

Can't you use an event object?

i.e.

 function myFunction (e) { var $this = $(e.currentTarget); }; 

Example: http://jsfiddle.net/gRoberts/cRnb3/

+1
source

you could read the currentTarget of the passed object, for example:

 function myFunction (event) { var $this = $(event.currentTarget); etc etc }; $('.myClass1').one('keyup', myFunction); $('.myClass2').one('keyup', myFunction); etc 
0
source

try it

 function myFunction () { var $this = $(this); etc etc }; var obj= $('.myClass1'); obj.myFunction =myFunction ; obj.one('keyup', myFunction); obj.one('keyup', myFunction); etc 
0
source

Source: https://habr.com/ru/post/921373/


All Articles