2012-06-10 45 views
8

骨幹js中的View.remove()函數從DOM刪除視圖的容器元素,從而防止重新創建已刪除的視圖。任何想法,這種情況下如何處理在骨幹js中重新創建已刪除的視圖

這裏是我的代碼,

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」股利是不再存在。

回答

21

首先,你不需要你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確實,這意味着清理出的HTML 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/

+0

感謝您的回覆。但出於某種原因,類似於您的示例的代碼不起作用。我創建了http://jsfiddle.net/EnVmN/7/來說明我遇到的問題。任何想法我做錯了什麼。我正在重用你的AttributeView,但添加了ItemView,並試圖顯示和刪除分別點擊編輯和刪除圖標的屬性視圖。 – mzafer

+0

@mzafer:視圖的事件只能在視圖的「el」及其子項上工作,您的ItemView正在渲染爲「#項目」,但這不是ItemView的「el」,因此圖標上的點擊事件不會被髮送到ItemView:http://jsfiddle.net/ambiguous/KjC6x/ –

+0

非常感謝,它現在可以工作:)在這花了近兩天時間。 – mzafer

0

看看LayoutManager骨幹意見,這明白,當你刪除一個視圖(父 - 安全殼的意義,而不是對象的層次感),其子視圖也應該刪除。