简体   繁体   English

骨干网视图事件不起作用

[英]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). 我创建了一个简单的主干页面,它从服务器获取一些设置(JSON)并将其插入到表中(每行是一个settingModel实例)。

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. 但不会触发该事件,当我在input代码中使用内联onfocus="alert()"时,相同的事件onfocus="alert()"起作用。

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. 您正在使用View元素的HTML内容。 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. 这是因为Backbone使用事件委托语法来绑定视图事件处理程序。 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. 由于您要添加View内容的html表示形式,因此添加的元素不是View元素的后代,因此事件不会传播到View的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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