JavaScript – 骨干自定义事件

假设我有两个观点(paginationview和postsview)和一个集合(postscollection).每当在paginationview中单击.next按钮时,我调用postscollection中的下一个函数,并且post集合从服务器获取页面的帖子(代码简化了).现在在我的帖子中,我只想显示最后一页的帖子.我不想将我的视图绑定到集合中的“添加”事件,因为有更多的情况是“添加”到集合中.在我的postscollection中调用’nextPage’函数时,我需要在我的postview中调用’renderlist’函数.如何将这些功能连接在一起?

// paginationview

var PaginationView = Backbone.View.extend({
    events:{
        'click a.next' : 'next',},next: function() {
        this.collection.nextPage();
        return false;
    }
});

//集合

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);
    },});

解决方法

您可以为此目的使用您自己的活动.

在Collection.nextPage中,您将触发事件:

this.trigger('nextpage');

并且在initiazlie方法中,将函数绑定到此事件:

this.listenTo(this.collection,'nextpage',this.renderlist);

并且不要忘记将renderlist的上下文绑定到此(再次在初始化视图方法中):

_.bindAll(this,'render','rederlist');

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...