Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js: understanding browser event handling and view removing

I'm fiddling with a view and related model that look like that:

App.Views.Addresses         = App.Views.Addresses || {};
App.Views.Addresses.Address = Backbone.View.extend({

  events: {
    "click button#foo"             : "clear"
  },

  initialize: function(model){
                this.address = model.model;
                this.address.view = this;
                _.extend(this, Backbone.Events);
                this.render();
              },

  render:     function(){
                ... rendering stuff
              },

  clear:      function(){
                this.address.clear();
              }
});

and

var Address = Backbone.Model.extend({

  url:   function() {
           ... url stuff
         },

  clear: function(){
           this.destroy();
           this.view.remove();
         }
});

I'm facing two problems here. The first one:

I have a button with id="foo" in my source and would like the view to catch the 'click' event of this very button and fire the 'clear' event. Problem: This does not work.

Anyway calling 'clear' on my model by hand cleanly removes the data on the server but does not remove the view itself. Thats the second problem. Hopefully someone more experienced can enlighten me.

Thx in advance Felix

like image 346
GeorgieF Avatar asked Dec 22 '22 16:12

GeorgieF


1 Answers

First problem:

  • Your button must be inside the element rendered by the view.
    • backbone scope events to inner elements only
  • You must render your view within this.el element
    • backbone use that element for delegation

Second problem:

  • Use events to destroy your view
    • You should not store the view in the model. This is kind of a "no no" in MVC. Your model already emits a "remove" event when deleted. Your view should listen to it and behave accordingly.
  • You must remove your view element from the DOM yourself
    • This is not handled by backbone.

Other general comments:

  • Views already are extending Backbone.Events
  • Use this.model instead of this.address
like image 117
Julien Avatar answered Dec 28 '22 07:12

Julien