2017-07-17 31 views
0

我正在使用聚合物組件,在該組件中我有一個聊天框,在其中加載來自Firebase數據庫的消息。我希望包含消息的div在組件加載時滾動到底部,以便用戶可以看到最新的消息。滾動到聚合物組件上的div的底部準備就緒

但是,我無法滾動到ready()attached()生命週期方法中Polymer組件中的div的底部。我看到滾動正確發生的唯一時間是當我通過點擊我的「提交」按鈕(下面的代碼)手動觸發滾動。

在我的高分子2.0元,我有我的組件下面的代碼:

HTML

<!-- CONTAINER TO DISPLAY MESSAGES --> 
    <div id="messages_container"> 
    <template is="dom-repeat" items="{{messages}}" as="message"> 
      [[message.name]]: [[message.text]] 
    </template> 
    </div> 

    <!-- MESSAGE INPUT --> 
    <textarea 
    placeholder="Type your message here" 
    on-input="_onMessageInput"> 
    </textarea> 
    <paper-button raised id="submit" 
    on-tap="_submitMessage"> 
    Send 
    </paper-button> 

JS

ready(){ 
    super.ready(); 
    this._scrollToBottom(); //calling from ready or attached does not scroll the div to the bottom 

    //I have also tried Polymer.RenderStatus.afterNextRender(this,() => { this._scrollToBottom(); }); but that does not cause scrolling to occur consistently 
} 

/** 
* Observer triggered when messages are written to Firebase database 
*/ 
_onMessagesChanged(){ 
    this._scrollToBottom(); 
} 

_scrollToBottom(){ 
    this.$.messages_container.scrollTop = 
    this.$.messages_container.scrollHeight; 
} 

_submitMessage(){ 
    // store message in Firebase database code not shown 
    // this triggers onMessagesChanged(), which then correctly scrolls the div to the bottom 
} 

我看到的是,滾動到下行爲只發生當我點擊提交按鈕手動觸發_onMessagesChanged。但是,我沒有收到我的組件初始加載時的滾動行爲。

任何幫助,將不勝感激。

回答

0

您可以爲dom-repeat更改時設置偵聽器,因此永遠不必手動更新它。把這個放在你的屬性聲明之後:

listeners: {'dom-change': '_scrollToBottom'},