javascript Backbone.js:为什么这个事件没有绑定?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4909564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:20:10  来源:igfitidea点击:

Backbone.js: Why isn't this event bound?

javascriptbackbone.js

提问by Matt Darby

I have a simple todo list, and all is rendering as expected, but when I click on the submit button in the edit form, the form is submitted (GET /todo_items), and the page is reloaded an only shows the edit form. The "submit form" event isn't being bound and I can't figure out why. What am I missing?

我有一个简单的待办事项列表,一切都按预期呈现,但是当我单击编辑表单中的提交按钮时,表单被提交 (GET /todo_items),并且页面被重新加载并仅显示编辑表单。“提交表单”事件不受约束,我不知道为什么。我错过了什么?

App.Views.Edit = Backbone.View.extend({
  events: {
    "submit form": "save"
  },
  initialize: function(){
    this.render();
  },
  save: function(){
    var self = this;
    var msg  = this.model.isNew() ? 'Successfully created!' : 'Saved!';

    this.model.save({
      title: this.$('[name=title]').val(),

      success: function(model, resp){
        console.log('good');
        new App.Views.Notice({message: msg});
        self.model = model;
        self.render();
        self.delegateEvents();
        Backbone.history.saveLocation('todo_items/'+ model.id);
        $('#edit_area').html('');
      },
      error: function(){
        console.log('bad');
        new App.Views.Error();
      }
    });

    return false;
  },
  render: function(){
    $('#edit_area').html(ich.edit_form(this.model.toJSON()));
  }
});

Here's the edit form:

这是编辑表格:

<script id="edit_form" type="text/html">
  <form>
    <label for="title">Title:</label>
    <input name="title" type="text" value="{{title}}" />
    <button>Save</button>
  </form>
</script>

回答by Julien

Backbone uses delegateEvents on the el element. If you do not specify "el" or do not use "el" to render your view, the event delegation will not work. Instead of doing

Backbone 在 el 元素上使用 delegateEvents。如果您不指定“el”或不使用“el”来呈现您的视图,则事件委托将不起作用。而不是做

$("#edit_area") 

within your render, pass it as the "el" option in the constructor:

在渲染中,将其作为构造函数中的“el”选项传递:

edit = new App.Views.Edit({el: $("#edit_area")})

Refer to it as this.el everywhere in your view code, especially in your render.

在视图代码中的任何地方都将其称为 this.el,尤其是在渲染中。

回答by Matt Darby

After many hours of monkeying with this, it worked after I explicitly set elon the view, and used$(this.el)in the renderfunction. Weird.

经过几个小时的玩弄之后,它在我明确设置el视图并$(this.el)render函数中使用后起作用。奇怪的。