Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery callback - strict violation

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

I have a handler like so:

$('.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

It doesn't like it because in strict mode because I'm using this outside of a method. I get that.

However, I need to have myFunction separate to the handler, because (1) it's attached to various classes/elements and (2) I am using .off().one('keyup', myFunction) to reset the one handler for various classes at various points.

So how do I get around having a separate callback function without violating the this business?

like image 585
Nick Avatar asked Jul 26 '12 08:07

Nick


2 Answers

I get the basic idea about this not being in a method when in strict mode...

Yes, but you're confusing two unrelated things: Strict mode, and JSLint. They're largely unrelated (except that JSLint has an option to require strict mode).

There's no problem with your code in strict mode. It's perfectly valid and appropriate (because of how jQuery uses this). Example There is no "strict violation" there.

JSLint doesn't like it, but JSLint doesn't like a lot of things that are perfectly valid and appropriate. JSLint detects a combination of things that are very widely-acknowledged to be problems (like missing semicolons), and things that Douglas Crockford doesn't like from a style perspective. Crockford's intelligent and well-informed, but not everyone agrees with his style choices.

Lint tools are very helpful, an essential part of the toolkit. JSLint is less helpful than it might be (in my view), by conflating substance issues with style issues (although granted it's a fine line, with JavaScript). You might consider using JSHint, a fork which gives you more control over what it checks.

like image 157
T.J. Crowder Avatar answered Sep 22 '22 15:09

T.J. Crowder


Can't you use the event object instead?

i.e.

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

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

like image 43
Gavin Avatar answered Sep 21 '22 15:09

Gavin