2011-08-24 5 views
0

다음과 같이 간단한 JQuery 플러그인을 작성하려고합니다. $ ("div")와 같은 단일 요소를 전달해야합니다. applyPlugin(); 후 내가 전달 된 선택기의 각 통해 이동 사업부의 인스턴스에 로컬 간격을 설정해야하고, 지우기 시간 이상. 이 작업을 수행하는 데 도움이되는 플러그인을 작성하려고하지만 범위 지정 문제가있는 것 같아요.Jquery Plugin/Set interval and scoping issue

는 다시, 나는 설정에 사업부에 타이머를해야하고, 한 페이지에 10 번처럼 다시 사용할 수. 모든 div는 본질적으로 자신의 '타이머'를 갖게됩니다. 즉, div 위로 마우스를 가져 가면 해당 타이머가 지워집니다. 마우스를 끈 상태에서 타이머를 다시 시작하십시오.

플러그인에 내부 메소드를 사용하여 수행해야하는지, 아니면 더 쉽게/더 쉬운 방법으로 수행해야하는지 확실하지 않습니다. 내가 this- '

(function($){ 

var methods = { 
    init : function(options) { 
     /* init method */ 
     return setInterval($(this).boxit('update'),5000); 
    }, 
    show : function() { }, 
    hide : function() { }, 
    update : function(content) { 
     /* update method */ 
     console.log("ping"); 
    } 
}; 

$.fn.boxit = 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.tooltip'); 
    }   
}; 

})(jQuery); 

'

답변

0
나는 이것이 당신이 원하는하지 않은 경우 그렇게 용서 여기에 전체 잘못된 방향으로 갈 수

으로 지금까지에 어딘지 여기

이며, jQuery 객체에 대한 참조를 매개 변수로 전달할 수 있습니다.

(function($){ 

var methods = { 
    init : function(jqObject, options) { 
     /* init method */ 
     return setInterval(jqObject.boxit('update'),5000); 
    }, 
    show : function() { }, 
    hide : function() { }, 
    update : function(content) { 
     /* update method */ 
     console.log("ping"); 
    } 
}; 

$.fn.boxit = function(method) { 
    var args = Array.prototype.slice.call(arguments, 0); 
    args.splice(0, 0, $(this)); 

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

})(jQuery);