0

我有一个使用 Backbone.js 开发的 Web 应用程序。在应用程序中,有一些按钮可以删除内容视图,但在推送时不会删除内容模型。例如,如果我多次按下同一个按钮,内容会被替换,但不会删除该内容的模型。我怎样才能删除它?

我知道如何使用其他不同的按钮删除内容,但是如果按下相同的按钮(或其他不是注定要删除但要添加的按钮),我不知道如何删除内容。
示例代码:HTML:

<button class="ShowCam"></button>
<button class="camClose"></button>
<button class="anotherButton"></button>

JS:

var camContent = Backbone.View.extend({
        el: "body",     
    events: {
        "click .ShowCam": "addContentCam", 
                "click .anotherButton": "otherAddContentFunction"                   
    },          
    initialize: function() {
        _.bindAll(this);
        this.model = new ContentCollection();
        this.model.on("add", this.contentAdded);
        this.model.on("remove", this.removeContentCam); 
    },                  
    addContentCam: function(event) {
        this.model.add({ modelName: "IPcam"});          
    contentAdded: function(content) {
        if (content.view == null) {
           var templ_name = 'cam';                                                  
           content.view = new ContentView({
                  model: content,
                  template: $.trim($("[data-template='"+ templ_name +"'] div").html() || "Template not found!")});
           $("div.camBox").empty(); 
           this.$el.find(".content").find("div.camBox").append(content.view.render().el);                                           
        }                   
    },  
    removeContentCam: function(content) {
        if (content.view != null) { 
            content.view.remove();              
        }
        content.clear();  //Clear the properties of the model   
    }   
}); 
var ContentView = Backbone.View.extend({
    tagName: "div",
    template: null,
    events: {
          "click .camClose": "removeView" 
    },
    initialize: function() {
        _.bindAll(this);
        this.template = this.options.template; 
    },
    render: function() {        
        this.$el.html(Mustache.render(this.template, this.model.toJSON())); 
        return this; 
    },
    removeView: function() {
        this.model.collection.remove(this.model); //Remove the model of the collection
    }
});
4

1 回答 1

1

Javascript 使用垃圾收集系统来进行内存管理。这意味着您可以简单地通过删除对它的所有引用来删除任何内容(好吧,从技术上讲,在垃圾收集器到达它之前它实际上并没有被删除,但本质上它已被删除)。

因此,如果您想确保模型被移除,您不需要调用任何特殊方法,您只需对delete someView.model引用该模型的每个视图(或代码中的其他位置)执行操作即可。

如果您查看上的remove方法,您实际上可以在实践中看到所有这些Backbone.View。你会发现它真正做的(除了触发事件)就是调用一个内部方法_removeReference。有什么作用_removeReference?这个:

  if (this == model.collection) {
    delete model.collection;
  }
  // (there's also an event-related line here)

现在,话虽如此,如果您要创建一个新视图来替换旧视图,并且它们都具有相同的模型……那么您可能一开始就不应该创建一个新视图。处理这种情况的更标准的 Backbone 方法是在视图上重新调用渲染(而不是创建一个新的)。

于 2013-01-11T01:17:35.033 回答