2017-11-06 9 views
1

나는 Knockout.js의 초보자입니다.두 이벤트를 knockout.js의 요소에 바인딩하는 방법

기본적으로 이미지 버튼을 클릭 할 때 모달을 여는 코드 스 니펫이 있습니다. 어떤 이유로 키 누르기 작업을하지 않습니다.

<div class="text-center tooltip-lg"> 
    <a class="tooltip-container" tabindex="0"> 
     <i class="icon icon-pencil dynamic-icon tooltip_trigger" title="edit" data-toggle="modal" data-target="#assessment_type_modal" data-placement="top" data-bind="click: $root.opt.openModalForEdit"></i></a></div> 

가 키를 누를 때 또는의 keyup 이벤트가 실종 된 이후, 나는 아래의 변경을 :

다음은 초기 코드입니다.

<div class="text-center tooltip-lg"> 
    <a class="tooltip-container" tabindex="0"> 
     <i class="icon icon-pencil dynamic-icon tooltip_trigger" title="edit" data-toggle="modal" data-target="#assessment_type_modal" data-placement="top" data-bind="event: { click: $root.opt.openModalForEdit, keypress: $root.opt.openModalForEdit }" ></i></a></div> 

키 누르기로 동작이 트리거되지 않습니다. 나는 또한 (stackoverflow에있는 몇 가지 질문에서 언급 한 것처럼)뿐만 아니라 작동하지 않았 keyup 했어요.

The Model looks like this: 

viewModel.opt = { 
    openModalForNew: function() { 
     // Some code 
    }, 
    openModalForEdit: function (assessmentType) { 
     // Some code 
    }, 
    saveModal: function() { 
     // Some code 
    }, 
    removeAsmtType: removeAsmtType 
}; 

업데이트 : 작업이 인식되지만 이벤트가 트리거되지 않은 이유를 알 수 없습니다. 아래의 테스트 케이스를 실행할 때 마우스를 해당 태그 위로 가져갈 때마다 콘솔에 테스트가 인쇄됩니다.

<div class="text-center tooltip-lg"> 
    <a class="tooltip-container" tabindex="0"> 
     <i class="icon icon-pencil dynamic-icon tooltip_trigger" title="edit" data-toggle="modal" data-target="#assessment_type_modal" data-placement="top" data-bind="event: { click: $root.opt.openModalForEdit, 'mouseover' : function() { console.log('TEST'); return true; }" ></i></a></div> 

내가 잘못하고있는 것이 무엇인지 제안 할 수 있습니까? 브라우저 콘솔에도 오류가 표시되지 않습니다.

미리 감사드립니다.

+0

당신은 조각을 만들거나 바이올린 수 있습니까? – Nisarg

답변

1

keypress 이벤트는 포커스가있는 요소, 즉 : tabindex (또는 contenteditable) 속성을 갖거나 (모든 <input> 요소 등)를 자동으로 지원하는 요소에 트리거됩니다.

event: { keypress: ... } 바인딩을 인 <a> 요소로 이동하여 문제를 해결할 수 있습니다.

ko.applyBindings({ 
 
    onPress: function(d, e) { 
 
    console.log("keypress on node", e.target.nodeName); 
 
    } 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> 
 

 
<p>Tap the text and press a key. The console will log the element that has the keypress event</p> 
 
<a tabindex="0" data-bind="event: { 
 
    keypress: onPress 
 
}"> 
 

 
    <i data-bind="event: { 
 
    keypress: onPress 
 
    }">some text</i> 
 
</a>

+0

귀하의 솔루션 구현에 문제가 있습니다. 태그의 속성은 자바 스크립트 라이브러리 knockout.js가 사용자가 "수정"연필 아이콘을 클릭 할 때 모달 대화 상자 창을 표시하는 데 사용됩니다. 어떻게 해결할 수 있습니까? 미리 감사드립니다. –

+0

이상적으로 DOM의 모든 속성 값은 기본 * viewmodel *에 이미 있습니다. 빠른 수정이 필요하면'e.target.querySelector ("i")'를 사용하여 요소를 선택할 수 있지만 권장하지는 않습니다. – user3297291