Backbone.js:为什么这个事件没有绑定? [英] Backbone.js: Why isn't this event bound?

查看:25
本文介绍了Backbone.js:为什么这个事件没有绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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()));
  }
});

这是编辑表单:

<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>

推荐答案

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

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

$("#edit_area") 

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

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

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

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

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

这篇关于Backbone.js:为什么这个事件没有绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆