在主干js中重新创建已删除的视图 [英] Recreating a removed view in backbone js

查看:18
本文介绍了在主干js中重新创建已删除的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The View.remove() function in backbone js removes the container element of the view itself from the DOM preventing from recreating views that have been removed. Any idea how this scenario is handled

这是我的代码,

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 不再存在.

The last two lines above do not recreate the view as the div with id="attrs" is not longer there.

推荐答案

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

First of all, you don't need your dispose method, the standard remove is sufficient:

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

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

Secondly, you can override remove if the standard version doesn't do what you need. The default implementation simply removes this.el and cleans up some event listeners:

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

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

In your case, you want to undo everything that render does and that means clearing out the HTML inside this.el and removing the events by calling undelegateEvents:

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

然后你可以调用 attrView.remove() 并关闭它,然后 (new AttributeView()).render() 把它带回来.

Then you can call attrView.remove() and kill it off and (new AttributeView()).render() to bring it back.

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

这篇关于在主干js中重新创建已删除的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆