timpone
timpone

Reputation: 19969

backbone.js removing template from DOM upon success

I'm writing a simple message board app to learn backbone. It's going ok (a lot of the use of this isn't making sense) but am a little stuck in terms of how I would remove a form / html from the dom. I have included most of the code but you can see about 4 lines up from the bottom, the part that isn't working. How would I remove this from the DOM?

thx in advance

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');
      }
    });

Upvotes: 0

Views: 1411

Answers (1)

mu is too short
mu is too short

Reputation: 434845

Backbone doesn't call the success callback with any particular this, it is simply called as a plain function. So, this inside your success callback will be window rather than the view you're expecting it to be.

Any of the usual solutions will work:

  1. Save the desired this in a local variable:

    var _this = this;
    this.model.save(data, {
      success: function() {
        //...
        _this.remove();
    
  2. Use a bound function:

    this.model.save(data, {
      success: _(function() {
        //...
        this.remove();
      }).bind(this)
    
  3. Use a named bound function:

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

And the usual variations on the above.

Also note that I switched to View#remove since you are apparently trying to remove the whole view and that's the usual way to do it.

Upvotes: 1

Related Questions