2013-02-18 3 views
1

addon 작성시 이벤트 기반 선택적 기능을 전달하는 방법은 무엇입니까? 함수의 이름을 호출 프로 시저의 문자열로 수동으로 작성한 다음 this.html()에 onclick = ""문자열로 추가하면됩니다.하지만 이는 naff입니다. 나는 성숙한 선택적 인수로 함수를 전달하고 선택적으로 클릭 조건부 이벤트jQuery 플러그인 - 옵션에서 함수 전달 - 이벤트로 실행

문서

<div id="grid"></div> 
<script>  
$(function() { 
    $("#grid").myaddon({ 
     "headings" : [ 
      { 
       "title" : "hello", 
       "click_callback" : function(){ 
        alert('hi'); 
       } 
      }, 
      { 
       "title" : "there" 
      } 
     ] 
    }); 
}); 
</script> 

및 부가 기능 자체

(function($) { 

    var methods = { 
     init : function(options) { 

      var defaults = { 
       "title": "text", 
       "click_callback": function() {} 
      } 
      for(var i=0; i<options.headings.length; i++) { 
       var heading = $.extend({},defaults,options.headings[i]); 
       this.html("<div id=\"addon"+(parseInt(i))+"\" >" + heading.title + "</div>"); 
       if (typeof heading.click_callback == 'function') { 
        $("#addon"+(parseInt(i))).click(function() { heading.click_callback.call(this) }); //this doesn't work 
        $("#addon"+(parseInt(i))).click(function() { heading.click_callback.call() });  //this doesn't work 
        $("#addon"+(parseInt(i))).click(heading.click_callback.call());     //this doesn't work 
        $("#addon"+(parseInt(i))).click(eval(heading.click_callback.call()));    //(in desperation) this doesn't work 

        //(edit) 
        $("#addon"+(parseInt(i))).click(heading.click_callback);    //(!!thanks Robert Fricke!) thanks to the answer from Robert Fricke I know this works 
        //(/edit) 
       } 
      }    
     } 
    } 
    $.fn.myaddon = function(method) { 

     // Method calling logic 
     if (methods[method]) { 
      return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); 
     } 
     else if (typeof method === 'object' || ! method) { 
      return methods.init.apply(this, arguments); 
     } 
     else { 
      $.error('Method ' + method + ' does not exist on jQuery.myaddon'); 
     } 
    }; 
})(jQuery); 

답변

1

이러한 시도로 추가 할 :

$("#addon"+(parseInt(i))).click(heading.click_callback); 
$("#addon"+(parseInt(i))).click(function(){heading.click_callback();}); 
+0

와우! '$ ("# addon"+ (parseInt (i))). (heading.click_callback);을 클릭 해 주셔서 감사합니다. – user2083181