微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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');

原文地址:https://www.jb51.cc/js/155385.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐