18

Most of the times, I put some javascript code in $(document).ready to do some initialization stuffs on the page, like event binding, etc.

But now I would like to use pjax https://github.com/defunkt/jquery-pjax for some of my pages.

With pjax, because there's only part of the page gets refreshed, $(document).ready will not get called again.

I could manually trigger the initializing script on event pjax:end, but I also want to know if there's a better solution for that.

Thanks.

4

3 回答 3

57

您可以轻松地将所有现有代码链接到 document.ready 和 pjax:success 事件,如下所示:

前:

$(document).ready(function() {
    // page load stuff
});

后:

$(document).on('ready pjax:success', function() {
    // will fire on initial page load, and subsequent PJAX page loads
});
于 2012-05-16T07:10:51.600 回答
4

我想出了这个巧妙的解决方案。您首先在全局范围内为您的活页夹创建一个命名空间:

// 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对象以添加与您的路由名称匹配的功能。例如,在http://www.yourdomain.com/admin通过 PJAX 访问时,将在全局范围内调用 this:

$.extend($.fn.bindPJAX, {
  admin: function(){
    // Initialization script for /admin route
  }
});

当 PJAX 失败或不受支持时,您还应该考虑可行的 DRY 回退,例如通过签window.location入 javascript 在第一个页面加载时启动正确的 init 函数,或者在应用程序的视图中对其进行硬编码。

于 2013-02-18T08:29:45.523 回答
0

I think your best bet is probably just to do what you said and hook your page specific init code up to the "pjax:end" event. That way it'll essentially be doing the same job that it did before and run against whatever html has been loaded in to the DOM.

于 2012-03-19T13:26:35.920 回答