Backbone.js: understanding browser event handling and deletion

I was messing around with the view and its related model, which looks like this:

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 have two problems here. First:

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

In any case, calling "clear" on my model manually clears the data on the server, but does not delete it. This is the second problem. Hope someone more experienced can enlighten me.

thanks in advance felix

+4
source share
1 answer

First problem:

  • Your button should be inside the item displayed in the view.
    • main area events for internal elements only
  • You must display your view in this this.el element.
    • server uses this item for delegation

The second problem:

  • Using events to destroy your view
    • You should not save the view in the model. This is kind of a no in MVC. Your model already deletes the delete event on deletion. Your opinion should listen to it and behave accordingly.
  • You must remove your view from the DOM yourself
    • This is not handled by the backbone network.

Other general comments:

  • Views already extend Backbone.Events
  • Use this.model instead of this.address
+11
source

Source: https://habr.com/ru/post/1344575/


All Articles