【问题标题】:Recreating a removed view in backbone js在主干 js 中重新创建已删除的视图
【发布时间】:2012-06-10 04:51:47
【问题描述】:

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

这是我的代码,

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

上面的最后两行不会重新创建视图,因为 id="attrs" 的 div 不再存在。

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

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

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

    其次,如果标准版本不能满足您的需求,您可以覆盖 removedefault implementation 只是删除了this.el 并清理了一些事件监听器:

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

    在您的情况下,您希望撤消 render 所做的一切,这意味着清除 HTML inside this.el 并通过调用 undelegateEvents 删除事件:

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

    然后你可以打电话给attrView.remove() 把它干掉,然后(new AttributeView()).render() 把它带回来。

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

    【讨论】:

    • 感谢您的回复。但是由于某种原因,类似于您的示例的代码不起作用。我创建了jsfiddle.net/EnVmN/7 来说明我遇到的问题。知道我做错了什么。我正在重用您的 AttributeView 但添加了 ItemView 并尝试分别在单击编辑和删除图标时显示和删除属性视图。
    • @mzafer:视图的事件仅适用于视图的 el 及其子视图,您的 ItemView 正在渲染为 #items 但那不是 ItemView 的 el 所以图标上的点击事件没有被发送到 ItemView:jsfiddle.net/ambiguous/KjC6x
    • 一年后,您仍在挽救生命 - 感谢您的支持。一直在下午:)
    【解决方案2】:

    查看 LayoutManager 的 Backbone Views,它了解当您删除视图(父级 - 在包含意义上,而不是对象层次结构意义上)时,它的子视图也应该被删除。

    【讨论】:

      猜你喜欢
      • 2012-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多