2011-05-03 1 views
0

이것은 조금 비표준일지도 모른다 .....jQuery : Plugin에서 객체로 사용할 문자열 참조를 전달한다.

// JavaScript Document 
(function($){ 
$.fn.editAsPage = function(options) {  
    var settings = {};  
    if(options){ jQuery.extend(settings, options); }   
    return this.each(function(){   
     var el = jQuery(this); 
     alert(settings.source.attr("class"));       
    }); 
}; 
})(jQuery); 

내 질문은 settings.source 매개 변수에있다. attr ("class")는 단지 예일 뿐이므로 특정 DOM 요소에서 얻는 데 필요한 몇 가지 속성이 있지만 플러그 인 사용자는 어떤 DOM 요소 settings.source가 필요한지 정의해야 할 수 있습니다.

그러면 jQuery 객체를 전달하면됩니다. 내가 문제가되는 부분은 필자가 플러그인에서 "this"의 부모를 참조하려고한다는 것입니다.

예 :

jQuery(".edit").editAsPage({ 
     'source':jQuery(this)                
    }); 

여기에서 jQuery (this)는 editAsPage 함수를 호출하기 전에 해석 할 것이므로 .edit 클래스가있는 요소를 참조하지 않습니다.

질문 : 플러그인에서 jQuery 객체로 해석되도록 editAsPage 함수에 문자열을 전달할 수 있습니까?

이것은 아주 간단한 예입니다. 플러그인에서 "this"를 사용하는 이유는 "소스"가 변경 될 수 있기 때문입니다. 그것은 아주 잘 될 수 있습니다 :

'source': jQuery (this) .parents ("selector : first")

그것은 내 마음에 의미가 있습니다. :)

고마워.

답변

1

콜백을 사용해야합니다. 첫 번째 단계는 source을 콜백으로 설정하여 이것이 어떻게 작동해야하는지에 대한 생각을 바꾸는 것입니다. 다음으로 call() mtheod (적용 가능한 경우 apply())를 사용하여 source을 수정하여 this 정의를 새로 전달해야합니다. 라이브와 http://jsbin.com/ipafe4

재생 :

$('.edit').editAsPage({ 
    source:function(){ 
    $('.parent').append('<strong>#'+$(this).parent().attr('id')+'</strong>'); 
    $('.id').append('<strong>#'+$(this).attr('id')+'</strong>'); 
    } 
}); 

여기에 라이브 예를 참조하십시오

(function($){ 
$.fn.editAsPage = function(options) {  
    var settings = {};  
    if(options){ jQuery.extend(settings, options); }   
    return this.each(function(){   
     var el = jQuery(this); 
     settings.source.call(this, el);      
    }); 
}; 
})(jQuery); 

사용자가 다음과 같이 사용합니다 : 모양은 수정

귀하의 플러그인 코드 여기에있는 예 : http://jsbin.com/ipafe4/edit

그때 ""은 사용자가 정의하고있는 source 함수/콜백으로 되돌려 놓은 것을 의미합니다.

정보 : http://www.pagecolumn.com/javascript/apply_call.htm

+0

물론. 감사. –

관련 문제