jQuery 데이터 $(…).data('foo')가 Backbone 앱에서 정의되지 않은 상태로 반환되는 경우가 있습니다.

StackOverflow https://stackoverflow.com//questions/22079847

문제

이상한 버그가 발생했습니다. 따라서 내 페이지에 'data-tagtype'으로 정의된 속성이 있습니다. button 내 HTML의 요소.사용자가 버튼을 클릭하면 다음 메서드가 호출됩니다.

onClickTag: function(e) {
  if (!this.playerLoaded) {
    return false;
  }
  var type = $(e.target).data('tagtype');
  var seconds = this.getCurrentTime();
  console.log(type);
  if (type) {
    this.model.addTag({
      type: type,
      seconds: seconds
    });
  }
},

이것은 작동합니다 최대 하지만 가끔은 어떤 이유로든 type (겉으로는) 임의의 요소에 대해서는 정의되지 않았습니다.해당 HTML은 다음과 같습니다.

<button id="tag-love" class="tagger disabled" data-tagtype="love"><i class="fa fa-heart fa-fw"></i></button>
<button id="tag-important" class="tagger disabled" data-tagtype="important"><i class="fa fa-exclamation fa-fw"></i> Important</button>
<button id="tag-more" class="tagger disabled" data-tagtype="more"><i class="fa fa-ellipsis-h fa-fw"></i> More</button>
<button id="tag-confused" class="tagger disabled" data-tagtype="confused"><i class="fa fa-question fa-fw"></i> Confused</button>

언제 반환되는지에 대한 패턴이 없는 것 같아서 이상합니다.때로는 모두 작동하고 때로는 그 중 하나가 몇 초 동안 정의되지 않은 상태를 반환하지만 계속 클릭하면 적절한 값이 반환됩니다.

뷰는 이러한 메서드가 호출되기 전에 확실히 DOM에 렌더링/로드됩니다.

어떤 아이디어가 있나요?Backbone이 뭔가를 할 수 있을까요?

도움이 되었습니까?

해결책

문제는 Backbone 뷰가 이벤트 처리를 위해 이벤트 위임을 사용한다는 것입니다.즉, e.target 이벤트에 응답하는 요소가 아니라 클릭되는 요소가 됩니다.다음을 클릭하면 <i>, e.target 그럴 것이다 <i> 하지만 텍스트를 클릭하면 e.target 될 것이다 <button>;그만큼 <i> 찾고 있는 데이터 속성이 없지만 <button> 하다.즉 가끔은 $(e.target).data('tagtype') 될거야 undefined.

간단한 예에서 이 동작을 볼 수 있습니다.

<div id="x">
    <button type="button" data-tagtype="love"><i>icon</i> text</button>
</div>

그리고 최소한의 보기:

var V = Backbone.View.extend({
    el: '#x',
    events: {
        'click button': 'clicked'
    },
    clicked: function(ev) {
        console.log(
            $(ev.target).data('tagtype'),
            $(ev.currentTarget).data('tagtype')
        );
    }
});

데모: http://jsfiddle.net/ambiguous/pe77p/

클릭하면 <i>icon</i>, 당신은 얻을 것이다 undefined love 콘솔에서 text, 당신은 얻을 것이다 love love 콘솔에서.

이 작은 데모에는 솔루션도 포함되어 있습니다.사용 e.currentTarget 대신에 e.target.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top