Giả sử tôi có hai chế độ xem (paginationview và postsview) và một bộ sưu tập (postscollection). Bất cứ khi nào nút .next được nhấp trong paginationview tôi đang gọi hàm tiếp theo trong postscollection và bộ sưu tập bài viết đang tìm nạp các bài viết của trang mới từ máy chủ (mã được đơn giản hóa). Bây giờ trong chế độ xem bài đăng của tôi, tôi chỉ muốn hiển thị các bài đăng ở trang cuối cùng. Tôi không muốn liên kết chế độ xem của tôi với sự kiện 'thêm' trong bộ sưu tập vì có nhiều trường hợp hơn một số thứ được thêm vào bộ sưu tập. Tôi muốn chức năng 'renderlist' trong postsview của tôi chỉ được gọi khi hàm 'nextPage' được gọi trong postscollection của tôi. Làm cách nào để kết nối các chức năng này với nhau?Sự kiện tùy chỉnh xương sống
// paginationview
var PaginationView = Backbone.View.extend({
events:{
'click a.next' : 'next',
},
next: function() {
this.collection.nextPage();
return false;
}
});
// thu
var PostsCollection = Backbone.Collection.extend({
model: model,
initialize: function() {
_.bindAll(this, 'parse', 'url', 'pageInfo', 'nextPage', 'previousPage');
this.page = 1;
this.fetch();
},
parse: function(response) {
console.log(response);
this.page = response.page;
this.perPage = response.perPage;
this.total = response.total;
this.noofpages =response.noofpages;
return response.posts;
},
url: function() {
return '/tweet/' + '?' + $.param({page: this.page});
},
nextPage: function() {
console.log("next page is called");
this.page = this.page + 1;
this.fetch();
},
// postsview
var PostsView = Backbone.View.extend({
events:{
'click #testbutton' : 'test',
'click #allbutton' : 'render',
},
initialize: function() {
this.listenTo(this.collection, 'add', this.addOne);
},
render: function() {
$(".maincontainer").html("");
this.collection.forEach(this.addOne, this);
return this;
},
renderlist: function(){
$(".maincontainer").html("");
this.collection.forEach(this.addOne, this);
},
addOne: function(post) {
var post = new postView({model : post});
post.render();
this.$el.prepend(post.el);
},
});
Có thể bạn nên lưu ý rằng 'this.tr igger ('nextpage'); 'có lẽ nên xảy ra trong trình xử lý thành công để tìm nạp. –
ý của bạn là gì? nó sẽ chỉ xảy ra nếu tìm nạp thành công? nếu không renderlist có thể được gọi trước khi tìm nạp? –
Vâng, Andrew đã đúng. Chúng ta nên đợi cho đến khi tìm nạp xong. Vì vậy, chúng tôi có thể kích hoạt sự kiện thành công. –