按下浏览器后退按钮时取消选中视图事件

时间:2016-05-24 13:04:24

标签: backbone.js backbone-views backbone-events

有人可以解释一下如何删除事件以防止在单击浏览器后退按钮时触发重复。或者有什么方法可以在重新审视视图时取消事件。真的陷入了如何处理它。 按后退按钮然后再返回会导致多次触发事件。例如,保存模型表单数据时。谢谢。

var App = {};

// extending models, collections etc.

App.SamplesCollectionView = Backbone.View.extend({

    el: '#samples',
    template: _.template($('#sample-edit-template').html()),
    events: {
        'click a.sample-item': 'onEdit'
    },
    render: function(){
        this.$el.append(this.template());
        var $sample_list = this.$el.find('ul#sample-list');
        this.collection.each(function(sample) {
            var rendered = new App.CategoryView({model: sample}).render().el;
            $sample_list.append(rendered);
        });
    },

    onEdit: function(e) {
        this.undelegateEvents();
        // go to edit view
        Backbone.history.navigate(e.target.getAttribute('href'), {trigger: true});
        return false;
    }

});

App.SampleEditView = Backbone.View.extend({

    el: '#samples',
    template: _.template($('#sample-edit-template').html()),
    events: {
        'click button.save': 'onSave',
        'click button.cancel': 'onCancel',
    },

    render: function() {
        this.$el.append(this.template(this.model.toJSON()));
        return this;
    },

    onSave: function() {
        this.undelegateEvents();
        var data = Helpers.getFormData(this.$el.find('form'));
        this.model.save(data);
        // go back to index view
        Backbone.history.navigate('/samples', {trigger: true});
        return false;
    }

});

App.SamplesRouter = Backbone.Router.extend({
    routes: {
        'samples': 'index',
        'samples/edit/:id': 'edit'
    },

    index: function() {
        App.samples = new App.SamplesCollection;
        App.samplessView = new App.SamplesCollectionView({collection: App.samples});
    },

    edit: function(id) {
        App.sampleEdit = new App.SampleEdit({id: id});
        App.sampleEditView = new App.SampleEditView({model: App.sampleEdit})
    }

});

App.samplesRouter = new App.SamplesRouter;

Backbone.history.start({pushState: true, hashChange: false});

1 个答案:

答案 0 :(得分:1)

问题是您有许多指向同一元素#samples的视图。您无法删除一个视图,因为如果您调用view.remove(),则其他视图的元素已消失 只要该元素存在于DOM中,您认为已经消失的视图将存在于内存中,因为共享元素具有引用视图实例的事件处理程序。

如果要在同一元素下委派显示功能和编辑功能,请使用show / hide技术在同一视图中执行此操作,而不创建新的视图实例。

否则他们应该有自己的元素,你不应该有两个指向同一元素的视图实例。切换到不同的视图时,请确保调用它的remove()方法,该方法从DOM中删除元素并调用undelegateEvents,以便正确收集垃圾。

相关问题