【发布时间】:2020-07-13 23:03:48
【问题描述】:
我想在我的Ruby on Rails 应用程序中构建无限滚动功能。为了实现它,我使用Stimulus JS(更多信息:here)、vanilla-lazyload js(更多信息:here)和pagygem(更多信息:here)(包括webpacker) .一切都很好,但是,vanilla-lazyload js 似乎停止了无限滚动。
这是我的设置。 index 查看(我使用 HAML):
%section(class="section section--tight" data-controller="infinite-scroll")
%div(class="section-body")
%div(class="content content--shot")
%div(class="shots-grid" data-target="infinite-scroll.entries")
= render partial: "shots/shot", collection: @shots, cache: true
%div(class="section-pagination")
%div(class="content")
%div(data-target="infinite-scroll.pagination")
!= pagy_nav @pagy
JS 控制器 - infinite_scroll_controller.js:
import { Controller } from "stimulus"
export default class extends Controller {
static targets = ["entries", "pagination"]
initialize() {
let options = {
rootMargin: '500px',
}
this.intersectionObserver = new IntersectionObserver(entries => this.processIntersectionEntries(entries), options)
}
connect() {
this.intersectionObserver.observe(this.paginationTarget)
}
disconnect() {
this.intersectionObserver.unobserve(this.paginationTarget)
}
processIntersectionEntries(entries) {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.loadMore()
}
})
}
loadMore() {
let next_page = this.paginationTarget.querySelector("a[rel='next']")
if (next_page == null) { return }
let url = next_page.href
Rails.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: (data) => {
this.entriesTarget.insertAdjacentHTML('beforeend', data.entries)
this.paginationTarget.innerHTML = data.pagination
}
})
}
}
懒加载vanilla-lazyload:
// https://github.com/verlok/lazyload
import LazyLoad from "vanilla-lazyload";
document.addEventListener('turbolinks:load', () => {
var lazyLoadInstance = new LazyLoad({
elements_selector: ".lazy",
cancel_on_exit: true,
use_native: false
});
})
控制器视图:
def index
@pagy, @shots = pagy Shot.is_recent.includes(:user).all
respond_to do |format|
format.html
format.json {
render json: { entries: render_to_string(partial: "shots/shot", collection: @shots, formats: [:html]), pagination: view_context.pagy_nav(@pagy) }
}
end
end
pagy gem 网站说 gem 需要设置 webpacker,[这里是链接][4]。但是,这似乎是turbolinks 中的问题。换句话说,vanillay-lazyload 适用于前 10 条记录,但是,对于新添加的(来自分页页面的记录)记录,它拒绝工作。也许我错过了什么?感谢您的帮助和时间。
【问题讨论】:
标签: javascript ruby-on-rails ruby turbolinks