2012-03-16 156 views
0

在這種情況下,它不會觸發Http方法刪除螢火蟲當我點擊清除,即使元素從DOM中刪除。骨幹刪除模型

var DecisionItemView = Backbone.View.extend({ 
     tagName: "li", 
     template: _.template($('#item-template').html()), 
     initialize: function() { 
      this.model.bind('change', this.render, this); 
      this.model.bind('destroy', this.remove, this); 
     }, 
     events:{ 
      "click span.decision-destroy": "clear" 
     }, 
     render: function() { 
      $(this.el).html(this.template(this.model.toJSON())); 
      return this; 
     }, 
     clear: function() { 
      var answer = confirm("Are you sure you want to delete this decision?"); 
      if (answer) { 
       this.model.destroy({ 
        success: function() { 
         console.log("delete was a success"); 
        } 
       }); 
      } 

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

回答

2

您的模型是否有ID?否則,destroy方法不會觸發一個http請求。

一些代碼來檢查這個

var M=Backbone.Model.extend({ 
    url:'/echo/json/' 
}); 

var DecisionItemView = Backbone.View.extend({ 
     tagName: "li", 
     initialize: function() { 
      this.model.bind('change', this.render, this); 
      this.model.bind('destroy', this.remove, this); 
     }, 
     events:{ 
      "click span.decision-destroy": "clear" 
     }, 
     render: function() { 
      var txt=(this.model.get("id")) ? "Clear with id":"Clear without id"; 
      $(this.el).html("<span class='decision-destroy'>"+txt+"</span>"); 
      return this; 
     }, 
     clear: function() { 
      var answer = confirm("Are you sure you want to delete this decision?"); 
      if (answer) { 
       this.model.destroy({ 
        success: function() { 
         console.log("delete was a success"); 
        } 
       }); 
      } 

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

var m1=new M({id:1}); var m2=new M(); 
var view1=new DecisionItemView({model:m1}); 
$("ul").append(view1.render().$el); 
var view2=new DecisionItemView({model:m2}); 
$("ul").append(view2.render().$el); 

並有小提琴http://jsfiddle.net/rSJP6/

+0

感謝您指出,如果模型沒有一個id屬性,該HTTP刪除方法不會被調用。我實際上需要銷燬一個模型而不進行HTTP Delete調用。爲了實現這一點,我只需在銷燬模型之前執行'this.unset(「id」);''。我發現Backbone文檔中沒有提到這種行爲,所以再次感謝。 – 2012-07-26 22:46:19