2013-11-03 69 views
2

我有一個問題讓iScroll(v5)與流星一起工作。我已經安裝了該軟件包沒有問題,但在文檔加載時調用iScroll會帶來一點痛苦。流星iScroll 5初始化

流星不支持身體的onload像iScroll演示,所以我嘗試:

if (Meteor.isClient) { 
    Meteor.startup(function() { 
    var myScroll; 
myScroll = new IScroll('#wrapper', { mouseWheel: true }); 
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false); 
}); 

}

在我main.js文件。

這似乎只在刷新頁面後才起作用,並且在導航到新頁面時不會運行。

我也嘗試添加初始化代碼到我的應用程序的主頁上的Template.rendered函數。它又似乎有時而不是其他人?

對不起,如果我是一個noob,但Meteors模板渲染很難讓我的頭。

任何人都可以提供幫助將非常感謝!

斯蒂芬

回答

4

你需要確保流星的反應渲染不會銷燬iScroll創建的DOM節點,並重新實例iScroll當他們被摧毀和重建。無論何時更改滾動條內的DOM,您都需要調用iScroll.refresh(),以便知道更新其尺寸。

讓我們通過一個例子 - 假設你有要滾動集合的模板:

<template name="myCollectionView"> 
    <div class="my_collection"> 
    <div class="scroller"> 
     {{#isolate}} 
     {{#each items}} 
      {{> item}} 
     {{/each}} 
     {{/isolate}} 
    </div> 
    </div> 
</template> 

請注意,你需要的div到雙繞您的收藏。傳遞給iScroll的外部div my_collection,以及實際上由iScroll的JS移動的單個內部div scroller

還要注意圍繞items#isolate塊 - 它告訴Meteor不要在該塊外傳播重新渲染,這樣,當集合發生變化時,外部DOM(包裝器和滾動器節點)不會被替換。

現在讓我們來初始化iScroll,並添加適當的簿記,以保持它運行時,DOM由流星的反應性的變化:

var scroller; // file-scope instance of iScroll that we will update appropriately 
... 
Template.myCollectionView.rendered = function() { 
    var scrollNode = this.find('.scroller'); 
    // let's figure out if iScroll is already running by checking whether 
    // it's DOM nodes are still intact. 
    if (scrollNode.style.webkitTransform == "") { 
    // either first time rendering, or someone replaced our DOM nodes. 
    // Re-instantiate iScroll. 
    scroller = new iScroll(this.find('.my_collection')); 
    } else { 
    // DOM is still intact, just tell iScroll to update its size 
    // You need to do this in a setTimeout to make sure DOM changes 
    // have already been rendered (this affects size computations) 
    Meteor.setTimeout(function() { scroller.refresh(); }, 0); 
    } 
} 

請確保您有在CSS overflow: hidden;組爲您的包裝股利(即.my_collection),你是很好去。

+0

謝謝列夫! 這是一個很好的答案;它不僅解決了我的問題,還顯示瞭解決方案背後的推理。 真的很感謝你的幫助 - 瞭解流星的渲染和腳本的重新初始化之間的關係在我希望在我的應用程序中實現的一些UI中是非常重要的。 乾杯! – Flatsteve