chernevik
chernevik

Reputation: 4000

How do I link a Backbone Form to an event?

I'm trying to implement a simple login form with Backbone, using the backbone-forms library.

$(function() {
  var LoginUser = Backbone.Model.extend({
    schema: {
      username: { type: 'Text'   },
      password: { type: 'Text'   }
    },
    url: 'login_backbone_form'
  });

  var thisLogin = new LoginUser();

  var form = new Backbone.Form({
    model: thisLogin,
    events: {
      "click button#formButton"   :   "saveForm"
    },

    saveForm: function() {
      alert('hit saveForm');
      this.model.save();
    }
  }).render();

  window.form = form;
  $('#formHook').html(form.el);
  $('<button type="button" name="login" id="formButton">Login</button>')
     .appendTo('#formHook');
});

My HTML has a div with id='formHook', and the page shows a form with a Login button. But hitting the button does nothing.

What am I doing wrong here?

Upvotes: 2

Views: 3356

Answers (1)

evilcelery
evilcelery

Reputation: 16149

The first problem could be that your form button is outside the context of the form view. When you attach DOM event handlers to a view, they will only respond to elements within that view. Try embedding the form and the button within a master view.

Here's the code and it's also in a JSFiddle here: http://jsfiddle.net/evilcelery/hsSru/

$(function() {
    var LoginUser = Backbone.Model.extend({
        schema: {
            username: {
                type: 'Text'
            },
            password: {
                type: 'Text'
            }
        },
        url: 'login_backbone_form'
    });

    var LoginView = Backbone.View.extend({
      events: {
          "click button#formButton": "saveForm"
      },

      initialize: function() {
        this.model = new LoginUser();
      },

      render: function() {
        var $button = $('<button type="button" name="login" id="formButton">Login</button>');

        this.form = new Backbone.Form({ model: this.model });

        this.$el.append(this.form.render().el);
        this.$el.append($button);

        return this;
      },

      saveForm: function() {
          this.form.commit();
          this.model.save();

          alert('hit saveForm');
          console.log(this.model.toJSON());
      }
    });

    window.loginView = new LoginView;
    $('#formHook').html(loginView.render().el);
});

Upvotes: 4

Related Questions