简体   繁体   中英

Backbone View events not working

I've created a simple backbone page, it fetches some settings (JSON) from server and inserts them in a table (each row is a settingModel instance).

Now I wanted to use events in order to change my models' attributes, when user changes them and sync settings with server.

I used the following code for the model's view:

app.settingView = Backbone.View.extend ({  // View for Model

  tagName: 'tr',

  template: _.template( $('#setting-template').html() ),

  events: {
    'focus input':'showAlert'
  },

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

  showAlert: function(){
    alert("You Are Editing");
  }
});

but it does not fire the event, the same event works when I used inline onfocus="alert()" in my input tag.

I created a fiddle here

That's because here:

$('.container').html($(settingsView.render().el).html());

you are using the HTML contents of the View's element. You should append the View's element itself.

$('.container').append(settingsView.render().el);

This is because Backbone uses event delegation syntax for binding the view event handlers. Since you are appending the html representation of View's contents the appended elements are not descendants of the View's element and as a result the event doesn't propagate to the View's element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM