"$ (). ready (handler)"가 권장되지 않는 이유는 무엇입니까?
로부터 jQuery를 API 문서 사이트 에 대한ready
다음 세 가지 구문은 모두 동일합니다.
- $ (문서) .ready (핸들러)
- $ (). ready (handler) (권장되지 않음)
- $ (핸들러)
숙제를 마치고 소스 코드를 읽고 놀았는데 왜 그런지 모르겠습니다.
$().ready(handler)
권장하지 않습니다. 첫 번째와 세 번째 방법은 정확히 동일하며 세 번째 옵션은 다음을 사용하여 캐시 된 jQuery 객체에서 ready 함수를 호출합니다 document
.
rootjQuery = jQuery(document);
...
...
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
그러나 ready 함수는 선택한 노드 요소의 선택기와 상호 작용하지 않습니다. ready
소스 코드 :
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.add( fn );
return this;
},
보시다시피 내부 queue ( readyList
)에 콜백을 추가 하고 집합의 요소를 변경하거나 사용하지 않습니다. 이를 통해 ready
모든 jQuery 객체 에서 함수 를 호출 할 수 있습니다 .
처럼:
- 일반 선택기 :
$('a').ready(handler)
DEMO - 말도 안되는 선택기 :
$('fdhjhjkdafdsjkjriohfjdnfj').ready(handler)
데모 - 정의되지 않은 선택기 :
$().ready(handler)
DEMO
마지막으로 ... 내 질문에 : 왜 $().ready(handler)
권장되지 않습니까?
jQuery 개발자 중 한 명으로부터 공식 답변을 받았습니다.
$().ready(fn)
(jQuery <1.4)에$()
대한 바로 가기 였기 때문에 작동 합니다. 그래서 읽기 쉬운 코드였습니다.$(document)
$().ready(fn)
하지만 사람들 $().mouseover()
은 다른 모든 종류의 광기 같은 일을했습니다 .
사람들은 $([])
빈 jQuery 객체를 얻기 위해해야 했습니다.
그래서 1.4에서 우리는 그것을 변경 $()
하여 빈 jQuery를 제공 $().ready(fn)
하고 많은 코드를 깨지 않도록 작업을했습니다.
$().ready(fn)
말 그대로 레거시 케이스에서 제대로 작동하도록 코어에 패치되었습니다.
ready
함수를 위한 가장 좋은 장소 는 $.ready(fn)
이지만, 이것은 정말 오래된 디자인 결정이며 지금 우리가 가지고있는 것입니다.
나는 그에게 물어 봤다:
$ (fn)이 $ (). ready (fn)보다 더 읽기 쉽다고 생각하십니까?!
그의 대답은 다음과 같습니다.
나는 항상 실제 앱에서 $ (document) .ready (fn)을 수행하며 일반적으로 앱에는 문서 준비 블록이 하나 뿐이며 유지 관리와 정확히 같지 않습니다.
나는 $ (fn)도 꽤 읽을 수 없다고 생각한다 . 그것은 단지 당신이 알아야 할 일이다. Works ™ ...
다른 옵션이 지적한 것과 거의 같은 일을하기 때문에 도서관 작가 모자를 쓰고 추측을 할 때입니다.
아마도 jQuery 사람들은
$()
향후 사용을 위해 사용할 수$().ready
있기를 원할 것입니다 (권장되지 않더라도 작동하도록 문서화 되었기 때문에 의심스럽고$
특수한 경우 의 의미를 오염시킬 수도 있습니다 ).훨씬 더 실용적인 이유 : 두 번째 버전은 래핑으로 끝나지 않는 유일한 버전
document
이므로 코드를 유지 관리 할 때 중단하기가 더 쉽습니다. 예:// BEFORE $(document).ready(foo); // AFTER: works $(document).ready(foo).on("click", "a", function() {});
이것을
// BEFORE $().ready(foo); // AFTER: breaks $().ready(foo).on("click", "a", function() {});
Related to the above:
ready
is a freak in the sense that it's (the only?) method that will work the same no matter what the jQuery object wraps (even if it does not wrap anything as is the case here). This is a major difference from the semantics of other jQuery methods, so specifically relying on this is rightly discouraged.Update: As Esailija's comment points out, from an engineering perspective
ready
should really be a static method exactly because it works like this.
Update #2: Digging at the source, it seems that at some point in the 1.4 branch $()
was changed to match $([])
, while in 1.3 it behaved like $(document)
. This change would reinforce the above justifications.
I would say its simply the fact that $()
returns an empty object whereas $(document)
does not so your applying ready()
to different things; it still works, but I would say its not intuitive.
$(document).ready(function(){}).prop("title") // the title
$().ready(function(){}).prop("title") //null - no backing document
More than likely this is just a documentation bug and should be fixed, the only downside to using $().ready(handler)
is it's readability. Sure, argue that $(handler)
is just as unreadable. I agree, that's why I don't use it.
You can also argue that one method is faster than another. However, how often do you call this method enough times in a row on a single page to notice a difference?
Ultimately it comes down to personal preference. There is no downside to using $().ready(handler)
other than the readability argument. I think the documentation is miss-leading in this case.
Just to make it patently obvious that there is some inconsistency in the three, plus I added the fourth often used form: (function($) {}(jQuery));
With this markup:
<div >one</div>
<div>two</div>
<div id='t'/>
and this code:
var howmanyEmpty = $().ready().find('*').length;
var howmanyHandler = $(function() {}).find('*').length;
var howmanyDoc = $(document).ready().find('*').length;
var howmanyPassed = (function($) { return $('*').length; }(jQuery));
var howmanyYuck = (function($) {}(jQuery));
var howmanyYuckType = (typeof howmanyYuck);
$(document).ready(function() {
$('#t').text(howmanyEmpty + ":" + howmanyHandler + ":"
+ howmanyDoc + ":" + howmanyPassed + ":" + howmanyYuckType);
});
The displayed results of the div from the last statement are: 0:9:9:9:undefined
SO, only the Handler and Doc versions are consistent with the jQuery convention of returning something of use as they get the document selector and with the Passed form you must return something (I wouldn't do this I would think, but put it in just to show "inside" it has something).
Here is a fiddle version of this for the curious: http://jsfiddle.net/az85G/
I think this is really more for readability than anything else.
This one isn't as expressive
$().ready(handler);
as
$(document).ready(handler)
Perhaps they are trying to promote some form of idiomatic jQuery.
참고URL : https://stackoverflow.com/questions/10753306/why-readyhandler-is-not-recommended
'program story' 카테고리의 다른 글
Visual Studio 프로젝트의 * .VC.db 파일은 무엇입니까? (0) | 2020.09.10 |
---|---|
Scala의 불변 집합이 유형에서 공변이 아닌 이유는 무엇입니까? (0) | 2020.09.10 |
Rails에서 동적 바인딩을 사용하여 원시 업데이트 SQL을 실행하는 방법 (0) | 2020.09.10 |
Java는 C ++의 std :: vector보다 배열을 사용하여 8 배 더 빠릅니다. (0) | 2020.09.10 |
ValueError : 수학 도메인 오류 (0) | 2020.09.10 |