2012-06-10 10 views
8

バックボーンjsのView.remove()関数は、ビュー自体のコンテナ要素をDOMから削除して、削除されたビューを再作成しないようにします。最後の2行は、上記のid =「attrsに」とdiv要素としてビューを再作成していないバックボーンで削除されたビューを再作成する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(); 

このシナリオでは、ここで

私のコードがある

の処理方法任意のアイデアは、もはやありません。

答えて

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が行うすべてのものを元に戻すと、それは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/

+0

ご返信ありがとうございます。しかし、何らかの理由であなたの例に似たコードが動作しません。私はhttp://jsfiddle.net/EnVmN/7/を作成して、私が持っている問題を説明しました。私が間違って何をしているのか。私はあなたのAttributeViewを再利用していますが、ItemViewを追加して、それぞれのアイコンの編集と削除をクリックするとattributeviewを表示して削除しようとしています。 – mzafer

+0

@mzafer:ビューのイベントはビューの 'el'とその子のみで動作しますが、ItemViewは'#items'にレンダリングされましたが、ItemViewの 'el'ではなく、アイコン上のクリックイベントはItemView:http://jsfiddle.net/ambiguous/KjC6x/ –

+0

ありがとう、それは今働いています:)これで約2日を費やしました。 – mzafer

0

は、ビューを削除するとことを理解している、バックボーン・ビューのためにLayoutManagerを見てみましょう(親 - 封じ込めの意味ではなくオブジェクト階層の意味)を、そのサブビューも削除する必要があります。

関連する問題