更改主干中的视图:超出最大调用堆栈

时间:2016-03-24 13:00:34

标签: javascript backbone.js

我在骨干应用程序中有一个视图,向用户解释他们没有任何要显示的数据,并单击按钮来创建一些数据。

创建一些数据会向我的服务器发送POST请求,然后将模型a添加到集合中,该集合上有一个监听器。

this.listenTo(this.collection, "add", this.addOneClient);

从上面你可以看到这会激发一个方法,

addOneClient: function(model) {

    if(this.collection.length == 1) {
        this.$el.empty(); 
        this.render();
    }

    var clientEntry = new Pops.Views.ClientListEntry({
        model : model,
        user : this.options.user
    });

    this.$('.client-list-table').append(clientEntry.render().el);
},

所以基本上它将一个视图添加到父视图中,但检查模型是否是集合中唯一的一个,就像它一样,我们需要删除无数据视图,并创建父视图,父视图是在render方法中创建,

render: function() {

        if(this.model.get('clients').length > 0) {

            this.$el.html( this.template({ //Originally Maximum callstack was being exceeded here
                organisation : this.model.toJSON(),
                user: this.options.user.toJSON()
            }));

        } else {

            var noView = new Pops.Views.NoView({
                text : "There are currently no clients, <a href='#' data-create='client'>click here</a> to create one."
            });

            return this.$el.html( noView.render().el );
        }

        var filter = Pops.Session.get('organisation_filters').findWhere({ organisation_id : this.model.get('id') });
        var sorting = filter.get('list_sorting').split(",");

        this.collection.sortByField(sorting[0], sorting[1]);

        this.$('.js-sort-client-projects').removeClass('active');

        if(sorting[1] == "desc") {
            this.$('.js-sort-client-projects[data-sort="' + sorting[0] + '"]').attr('data-order', 'asc');
            this.$('.js-sort-client-projects[data-sort="' + sorting[0] + '"]').removeClass('desc').addClass('asc active');
        } else {
            this.$('.js-sort-client-projects[data-sort="' + sorting[0] + '"]').attr('data-order', 'desc');
            this.$('.js-sort-client-projects[data-sort="' + sorting[0] + '"]').removeClass('asc').addClass('desc active');
        }

        this.addAll(); //Added this.$el.empty to addOne method, maximum callstack being exceeded here now.
    },

最初在render方法中超出了Maximimum调用堆栈,当我将模板推入this.$el时,我在我的addOneMethod中清空了。$ el,并在调用addAll时超出了调用堆栈方法,

addAll: function() {
        this.$('.client-list-table').find('tbody').empty();
        this.collection.each(this.addOneClient, this);
    },

我不知道我的代码有什么问题,任何人都可以解决问题吗?

1 个答案:

答案 0 :(得分:1)

嗯,我觉得这里有问题

addOneClient -> render -> addAll -> addOneClient