Pattle
Pattle

Reputation: 6014

Backbone bind model attribute to input

In Backbone is there a bind a model attribute to an input field so that when the input value changes the model attribute will be automatically set to the current value?

At the moment I have the following in my view

<input type="text" name="firstname" class="form-input" value="<%- model.firstname %>" />

Then in the view I listen to the following event and set the model attribute accordingly

events: {
    "keydown .form-input": "setAttribute"
},

setAttribute: function() {
    //Use model.set on the attribute that was changed
}

To me this seems like a bad way of doing it. Am I missing an easier way of doing it?

Upvotes: 3

Views: 1197

Answers (1)

joews
joews

Reputation: 30340

That's the right way to do it with vanilla Backbone. If you would like to set up automated data binding you'll need a plugin like Epoxy.

Using Epoxy, your example would look something like:

var BindingView = Backbone.Epoxy.View.extend({
  bindings: {
    "[name=firstname]": "value:firstName",
  }
});

This binds the model's firstName attribute to the input with name="firstname".

Upvotes: 4

Related Questions