javascript - 在 backbone js 中重新创建已删除的 View

标签 javascript backbone.js

backbone js 中的 View.remove() 函数从 DOM 中删除 View 本身的容器元素,防止重新创建已删除的 View 。知道如何处理这种情况

这是我的代码,

var AttributeView = Backbone.View.extend({
        el: $("#attrs"),
        template:_.template($('#attrs-template').html()),

        initialize:function() {
        },


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

        dispose:function(eventName){
            this.unbind();
            this.remove();
        },

    });


var attrView = new AttributeView();
....
attrView.dispose();
//Later on some event I do the below
attrView = new AttributeView()
attrView.render();

上面的最后两行没有重新创建 View ,因为带有 id="attrs"的 div 不再存在。

最佳答案

首先,您不需要dispose 方法,标准的remove 就足够了:

var attrView = new AttributeView();
//....
attrView.remove();  // <--------- Do this instead
//...
attrView = new AttributeView()
attrView.render();

其次,您可以覆盖 remove如果标准版本不能满足您的需求。 default implementation简单地删除 this.el 并清理一些事件监听器:

remove: function() {
  this.$el.remove();
  this.stopListening();
  return this;
},

在你的例子中,你想要撤消 render 所做的一切,这意味着清除 inside this.el 的 HTML 并删除通过调用事件 undelegateEvents :

remove: function() {
    this.undelegateEvents();
    this.$el.empty();
    this.stopListening();
    return this;
},

然后您可以调用 attrView.remove() 并将其杀死,然后调用 (new AttributeView()).render() 将其恢复。

演示:http://jsfiddle.net/ambiguous/Pu9a2/3/

关于javascript - 在 backbone js 中重新创建已删除的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10966440/

相关文章:

javascript - 如何使用 select 标签和 jquery 函数更改对 div 的内容进行排序

javascript - 如何让用户确认 ExtJs 中的组合框更改事件?

javascript - 按距离与钛合金型号排序

javascript - 有没有更好的方法将 "this"对象传递给回调函数?

Backbone.js 不会路由到与当前 URL 相同的 URL

backbone.js - 如何找到与点击的项目对应的模型ID?

javascript - Angular/Node 验证用户

javascript - Javascript 中的异步/等待

javascript - 当其中一个模型发生更改时,如何为 Backbone.js 中的 Collection View 附加事件处理程序?

javascript - 小数点后4位以上的数字相乘