0
當我使用傳遞給jQuery.animate()的自定義回調函數時,我有一個關於範圍設定的小問題。考慮下面的代碼。使用自定義回調時的Javascript範圍性能建議
;var WebApi = (function projectInit (WebApi, $, Modernizr, window, document, undefined) {
$(element).on('click.skiptodocumentpart', function skipToDocumentPart (e) {
WebApi.scrollTo(
$(this.getAttribute('href')).offset().top,
1000,
$pageNav.length ? repositionPageNav($pageNav, $(this)) : null
);
return false;
});
function repositionPageNav ($pageNav, $elm) {
console.log(this); // undefined
};
WebApi.scrollTo = function (yPos, iSpeed, callback) {
$('html,body').animate({
scrollTop : yPos
},{
duration : typeof iSpeed === 'number' ? iSpeed : 1000,
complete : typeof callback === 'function' ? callback : null
});
};
return WebApi;
}(WebApi || {}, jQuery, Modernizr, this, this.document));
當我登錄的repositionPageNav回調我得到一個不確定的,理想我想有上下文函數上下文引用的元素點擊,如jQuery的本身ussualy做。我可以通過改變回調調用WebApi.scrollTo如下做到這一點:
WebApi.scrollTo(
yPos,
1000,
as$pageNav.length ? (function (scope) {
return repositionPageNav.call(scope, $pageNav);
}(this)) : null
);
通過建立封閉的上下文中回調現指點擊,因爲我打算,但確實這個傷害的表現元素?而我無法理解的1件事是爲什麼在第一個示例中,上下文未定義?是否因爲我不會將回調稱爲callback.call(上下文)?任何建議/想法?
很多謝謝,
尼克。
啊上下文。我會確保記住這一點。在上面的例子中,傳遞的回調沒有執行直到animate()結束等待? – ngr 2013-02-19 17:20:48
如上所述,您不會傳遞任何回調。您立即調用該函數並傳遞結果('undefined')。 – Bergi 2013-02-19 17:24:03
所以通過傳遞它作爲repositionPageNav($ pageNav,$(this))它立即調用它?也許傳遞jQuery.proxy(repositionPageNav,上下文,參數)會更合適。 – ngr 2013-02-19 18:05:11