尝试按照本教程在轨道中创建带有刺激的无限滚动。这是我的观点:
<div data-controller="feed" data-action="scroll@window->feed#scroll" >
<div data-feed-target="entries">
<%= render(partial: "feed_posts")%>
</div>
<div data-feed-target="pagination" hidden>
<%== pagy_nav(@pagy)%>
</div>
</div>
我的导轨控制器:
def feed
@new_post = Post.new
@pagy, @posts = pagy(Post.where(user_id: current_user.all_following.pluck(:id)).or(Post.where(user_id: current_user.id)).order(created_at: :DESC), items: 5)
respond_to do |format|
format.html
format.json{
render json:{entries: render_to_string(partial: "feed_posts", formats: [:html]), pagination: view_context.pagy_nav(@pagy)}
}
end
end
最后是我的 js 控制器:
export default class extends Controller {
static targets = ["entries","pagination"]
scroll(){
let next_page = this.paginationTarget.querySelector("a[rel ='next']")
if(next_page == null ){ return }
let url = next_page.href
var body = document.body,
html = document.documentElement
var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight)
if(window.pageYOffset >= height - window.innerHeight - 100){
console.log("loading")
this.loadMore(url)
}
}
loadMore(url){
Rails.ajax({
type: 'Get',
url: url,
dataType: 'json',
success: (data) => {
console.log(data)
this.entriesTarget.insertAdjacentHTML('beforeend', data.entries);
this.paginationTarget.innerHTML = data.pagination
}
})
}
}`
负责查明是否点击页面底部的代码每次运行的次数不同,并且会向视图中添加太多结果。
我怎样才能让它有希望地运行一次,或者让它检查是否添加了 html,之前是否添加过......或者这可能不是一个好主意。