在Backbone中强制执行.destroy()

时间:2013-06-24 21:57:08

标签: backbone.js

我正在尝试在Backbone中对模型视图执行DELETE请求。但是,当单击链接时,Backbone正在执行GET请求。如何强制模型视图销毁模型而不是获取它?

玉/ HTML

script(type="text/template", id="allContactsTemplate").
  <td><%= first_name %></td>
  <td><%= last_name %></td>
  <td><%= email %></td>
  <td><%= description %></td>
  <td><a href="contacts/<%= _id %>" class="delete">Delete</a></td>

Backbone JS

// Single Contact View
App.Views.Contact = Backbone.View.extend({
  tagName: 'tr',

  template: template('allContactsTemplate'),

  events: {
    'click .delete': 'deleteContact'
  },

  initialize: function() {
    this.model.on( 'destroy', this.unrender, this);
  },

  render: function() {
    var template = this.template( this.model.toJSON() );
    this.$el.html( template );
    return this;
  },

  deleteContact: function() {
    this.model.destroy();
  },

  unrender: function() {
    this.remove();
  }
});

1 个答案:

答案 0 :(得分:0)

您没有在任何地方取消<a>的默认点击操作,因此点击.delete会做两件事:

  1. 调用应该触发DELETE请求的this.model.destroy()
  2. 触发通常的<a>行为,这将是GET contacts/some_id请求。
  3. 据推测,在AJAX DELETE有机会做任何事情之前,GET将接管浏览器。您应该以通常的方式取消<a>的默认操作:

    deleteContact: function(e) {
        e.preventDefault();
        this.model.destroy();
    }
    

    或:

    deleteContact: function() {
        this.model.destroy();
        return false;
    }
    

    您可能甚至不需要href <a>(除非您的CSS关心)。