2011-03-11 5 views
0

다른 방법으로 데이터를로드 할 수있는 플러그인이 있습니다. 나는 현재 올바른 기능을 실행하기 위해 플래그와 if을 사용하고 있습니다. 대신 어떻게 함수 포인터를 사용할 수 있는지 알아 내려고하고있다.다른 기능을 사용하여 데이터로드

$.fn.shureTable = function(options) { 
    var defaults = { 
     loadMethod: populateFromArray 
    }; 


    return this.each(function() { 
     var $this = $(this); 

     function loadJson(json) { 
      if (json.appendMode == 0) 
         jQuery('tbody', $this).empty(); 

      options.loadMethod(json.Rows); 
     } 
     function populateFromArray(rowArray){ 
     } 
    } 
} 

나는 오류가 populateFromArray가 정의되지 않은 것을 말하는 얻을 : 여기

은 조각이다. options을 사용하여 사용할 기능을 어떻게 제어 할 수 있습니까?

답변

0

범위 때문에 문제가 발생합니다. 이 함수는 각 문 안에 있기 때문에 사용할 수 없습니다.

그러나, 당신은 this과 같은 것을 사용할 수 있고 옵션 목록을 만든 다음 사용할 옵션을 전달합니다. 마찬가지로 사용자 정의 함수를 전달할 수 있도록 만들 수 있습니다.

<p id="red">Red colored</p> 
<p id="green">Green colored</p> 
<p id="blue">Blue colored</p> 

<div>This is a custom function</div> 

(function($){  
    $.fn.extend({ 
     color: function(method){ 
      // list of possible methods 
      var methods = { 
       red: function(a){ return '<span style="color:red;">'+a+'</span>' }, 
       green: function(a){ return '<span style="color:green;">'+a+'</span>' }, 
       blue: function(a){ return '<span style="color:blue;">'+a+'</span>' }, 
      } 
      // assign the appropriate function based on the "method" argument 
      var func = methods[method] || function(a){ return a; }; 

      // run through the elements and apply that function 
      return this.each(function(i,e){ 
       $(e).html(func($(e).html())); 
      }); 
     }, 
     color2: function(func){ 
      func = func || function(a){ return a; }; 
      return this.each(function(i,e){ 
       $(e).html(func($(e).html())); 
      }); 
     } 
    }); 
})(jQuery); 

$('p').each(function(i,e){ 
    $(e).color($(e).attr('id')); 
}); 

$('div').color2(function(a){ 
    return '<b style="color:#FF00FF">'+a+'</b>'; 
}); 

color

방법 검색된 개체의 이름을 전달할 수있다. color2은 전체 기능을 전달할 수 있으므로 사용자가 원하는 기능을 확장 할 수 있습니다. (매개 변수를 확인하고 인수의 유형에 따라 동작을 변경할 수는 있지만 데모 용입니다.)