I 이 깔끔한 해결책을 찾았습니다. 먼저 전역에서 바인더를위한 공간을 만들어 시작합니다
// Binder for PJAX init functions
$.fn.bindPJAX = {}; // Create namespace
function bindPJAX(functionName) {
// Check function existence, then call it
return $().bindPJAX[functionName] && $().bindPJAX[functionName]();
}
그런 다음 PJAX에 콜백을 결합하는 것은 클릭 :
$(document).ready(function(){
if ($.support.pjax) {
$('a[data-pjax]').on('click', function(event) {
var container = '#main';
var emptyRoute = 'feed'; // The function that will be called on domain's root
// Store current href without domain
var link = event.currentTarget.href.replace(/^.*\/\/[^\/]+\//, '');
var target = link === "" ? emptyRoute : link;
// Bind href-specific asynchronous initialization
$(document).on('ready pjax:success', container, function() {
bindPJAX(target); // Call initializers
$(document).off('ready pjax:success', container); // Unbind initialization
});
// PJAX-load the new content
$.pjax.click(event, {container: $(container)});
})
}
});
이이 설정되면, 당신은 $.fn.bindPJAX
을 확장 진행할 수 있습니다 경로 이름과 일치하는 함수를 추가하는 객체입니다. PJAX를 통해 http://www.yourdomain.com/admin
에 액세스 할 때 예를 들어,이는 전역 범위에서 호출됩니다 :
$.extend($.fn.bindPJAX, {
admin: function(){
// Initialization script for /admin route
}
});
PJAX가 실패하거나에서 올바른 init 함수를 실행처럼, 지원되지 않는 경우도 가능한 DRY 대체를 고려해야한다
첫 번째 페이지로드는 자바 스크립트에서 window.location
을 확인하거나 애플리케이션의보기에서 하드 코드 할 수 있습니다.
감사합니다. – neersighted
Loool. 그것을 좋아하십시오 :) – Zeck
초기화 코드가 각 페이지마다 다른 경우 어떻게해야합니까? – shreyj