jQuery callback - strict violation

喜你入骨 提交于 2019-12-10 13:43:25

问题


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?


回答1:


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.




回答2:


Can't you use the event object instead?

i.e.

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

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




回答3:


you could read the currentTarget of the event-object passed trough, like:

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



回答4:


Try this

function myFunction () {
    var $this = $(this);
    etc etc
};
var obj=  $('.myClass1');
obj.myFunction =myFunction ;

obj.one('keyup', myFunction);
obj.one('keyup', myFunction); etc


来源:https://stackoverflow.com/questions/11664958/jquery-callback-strict-violation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!