0

我正在编写一个简单的留言板应用程序来学习骨干。一切正常(很多使用这个没有意义)但是在我如何从 dom 中删除表单/html 方面有点卡住了。我已经包含了大部分代码,但您可以从底部向上看到大约 4 行,这部分代码不起作用。我将如何从 DOM 中删除它?

提前谢谢

var MbForm=Backbone.View.extend({
  events: {
  'click button.add-new-post': 'savePost'
  },

  el: $('#detail'),
  template:_.template($('#post-add-edit-tmpl').html()),
  render: function(){
    var compiled_template = this.template();
    this.$el.html(compiled_template);
    return this;
  },
  savePost: function(e){
    //var self=this;
    //console.log("I want you to say Hello!");
    data={
     header: $('#post_header').val(),
     detail: $('#post_detail').val(),
     forum_id: $('#forum_id').val(),
     post_id: $('#post_id').val(),
     parent_id: $('#parent_id').val()
    };

    this.model.save(data, {
      success: function(){
        alert('this saved');
        //$(this.el).html('this is what i want');
        this.$el.remove();//  <- this is the part that isn't working


       /* none of these worked - error Uncaught TypeError: Cannot call method 'unbind' of undefined 
        this.$el.unbind();
        this.$el.empty();

        this.el.unbind();
        this.el.empty();
       */

        //this.unbind();
        //self.append('this is appended');
      }
    });
4

1 回答 1

1

Backbone 不会success以任何特定的方式调用回调this,它只是作为普通函数调用。因此,this在您的success回调内部将是window而不是您期望的视图。

任何常用的解决方案都可以:

  1. 将所需的内容保存this在局部变量中:

    var _this = this;
    this.model.save(data, {
      success: function() {
        //...
        _this.remove();
    
  2. 使用绑定函数:

    this.model.save(data, {
      success: _(function() {
        //...
        this.remove();
      }).bind(this)
    
  3. 使用命名绑定函数:

    initialize: function() {
        _.bindAll(this, 'save_success');
    }
    //...
    this.model.save(data, {
      success: this.save_success
    

以及上述的通常变化。

另请注意,我切换到了,View#remove因为您显然是在尝试删除整个视图,这是通常的做法。

于 2012-12-08T17:37:55.177 回答