2013-07-16 2 views
0

JS 함수를 실행하고 "변경"또는 "클릭"과 같은 일부 jquery 이벤트에 바인딩해야하는 애플리케이션이 많은 곳이 있습니다. 리팩토링 목적으로이 작업을 수행하는 데 도움이되는 제네릭 함수를 만들고 싶습니다. 여기에 내 원래의 생각은 다음과 같습니다jQuery 변경을 매개 변수로 전달

function execute_and_track(trackEvent, action) { 
    action(); 
    trackEvent(function() { 
     action(); 
    }); 
} 

그리고 나는이 같이 사용할 생각 :

execute_and_track($("#ddl_Test").change, function() { 
    if ($("#ddl_Test").val().toUpperCase() == "OTHER") { 
     document.getElementById("txt_Test").style.display = "inline"; 
    } 
    else { 
     document.getElementById("txt_Test").style.display = "none"; 
     $("#txt_Test").val(""); 
    } 
}); 

불행하게도이 오류가 발생합니다 : catch되지 않은 형식 오류 : 개체 [글로벌 객체] '에'있는 방법이 없습니다. jquery 변경을 매개 변수로 전달할 수없는 것 같습니다. 아무도 나를이 논리를 수정하거나 이러한 리팩토링을위한 일반적인 함수를 만드는 또 다른 방법을 제안 할 수 있습니까?

답변

1

내가이 질문을 이해한다면, 나는 접근 방식을 바꿀 것이다.

는 여기에 플러그인 jQuery를 사용하는 것이 좋습니다 (jQuery 플러그인 등)이 새로운

$.fn.execute_and_track = function(eventName, func) { 
    this.each(function() { 
     func.call(this); // fix the scope 
     $(this).on(eventName,func); 
    }); 
    return this; 
} 

$("#ddl_Test").execute_and_track('change', function() { 
    if ($(this).val().toUpperCase() == "OTHER") { 
     this.style.display = "inline"; 
    } 
    else { 
     this.style.display = "none"; 
     $(this).val(""); 
    } 
}); 
+0

네보십시오. 그것은 잘 작동합니다. 감사. –