프로그래밍/JavaScript

jQuery의 data() 메소드의 캐싱이야기

seungdols 2017. 2. 26. 22:09

jQuery의 data() 메소드 사용 삽질기

jQuery에서 흔히 사용하는 것 중에 data()메소드입니다.

웹 개발을 하다보면, 특정 값을 서버에서 프론트로 내려 주어야 하거나, 하나의 뷰에 값만 바꾸어
동작하는 뷰 작업을 해야 하면 사용하게 되는 것이 data() 메소드입니다.

물론, 자바스크립트에서도 사용 할 수 있으나, 크로스 브라우징을 위해 jQuery를 사용하면 간편하게 크로스 브라우징 이슈를 해결 할 수 있습니다.
사실, 그래서 사용하는 거죠. Selector만 사용하기 위함이 아니라는 사실!!

jQuery는 JavaScript Library인데, 착각하는 것이 편한 셀렉터 지정으로 많이 사용하시는 줄 아시지만.
jQuery는 간편하게 JavaScript를 사용하게 만들되, 여러 브라우저에서도 동작하게 하는 것이 목표인 라이브러리입니다.

사설이 길었습니다…^^;;

아무튼 제가 최근에 겪은 일인데, data()를 사용하는데 이상한 일이었습니다.
특정 버튼 이벤트에 버튼에 있는 data를 계속 읽어오도록 작성을 했습니다.

jQuery('#wrap').on('click', 'btn_more', function(e)) {
    e.preventDefault();
    var btnId = jQuery(this).data('btn-id');
}

위 처럼 말이죠. 대신 버튼에 있는 btn-id 값은 다른 동작에 의해서 id 값이 변화됩니다.
그렇다면, 위 코드는 제대로 동작하지 않습니다.

왜냐!!!

jQuery의 data()메소드는 Caching을 하게 됩니다. 즉, 이미 jQuery chain내에 해당 하는 data()로 읽어온 값이 존재하면,
다음 호출에도 다시 접근 하지 않습니다.

위 질문의 답변 중 이런 답변이 나옵니다.

I ran into a similar “bug” a few days ago when working with .data() and .attr(‘data-name’) for HTML5 data attributes.
The behavior you’re describing is not a bug, but is by design.
The .data() call is special - not only does it retrieve HTML5 data attributes it also attempts to evaluate/parse the attributes. So with an attribute like data-myjson=’{“hello”:”world”}’ when retrieved via .data() will return an Object while retrieval via .attr() will return a string. See jsfiddle example.
Since .data() does extra processing jQuery stores the results of attribute evaluation in $.cache - after all, once a data attribute has been evaluated it would be wasteful to re-evaluate on every .data() call - especially since data variables can contain complex JSON strings.
I said all that to say the following: After retrieving an attribute via .data() any changes made by .attr(‘data-myvar’, ‘’) will not be seen by subsequent .data() calls. Test this out on jsfiddle.
To avoid this problem don’t intermix .data and .attr() calls. Use one or the other.

위 참고를 하시다 보면, jquery의 data() 메소드 자체가 그렇게 동작하도록 설계 되어 있다고 합니다.

즉, 지속적으로 변화하는 data 속성의 값을 읽어 오려면, 캐싱 된 값을 지워야 합니다.
그렇다면, 캐싱 된 값을 어떻게 지우느냐 ???!!!

jQuery('#btn_more').removeDate('btn-id');

removeData() 메소드를 이용해 캐싱 된 값을 지울 수 있습니다.

removeData() - API를 통해 해당하는 메소드의 사용법을 익힐 수 있습니다. 캐싱 된 값을 지운다기 보다는 해당하는 값자체를 날리는 걸로 생각하면 되며, 의미로 가장 정확한 캐싱 된 값만 지우는 방법은 또 다른게 있을 것 같습니다.

예제 코드를 원하신다면 작성하도록 하겠습니다.

읽어주셔서 감사합니다.

반응형

'프로그래밍 > JavaScript' 카테고리의 다른 글

Currying에 대해 알아보자.  (1) 2018.02.08
JavaScript Deferred 객체 Promise 패턴  (1) 2017.04.07
Jquery 초보의 적응기  (0) 2017.02.19
유투브 재생목록 제목 가져오기  (0) 2017.02.12
jQuery Event 관련 정리  (0) 2016.10.02