Get DOM element from template in backbone view

backbone.js, javascript, underscore.js

Solution

If every person is a different view instance with its own template, you can just define the scope of the selector for the view's template:

TEMPLATE

<form id="<%-id%>">
  <input value="<%-name%>" name="name"/>
  <input value="<%-age%>" name="age"/>
  <input value="<%-address%>" name="address"/>
  <button class=".save">Save</button>
</form>

VIEW

events:{
    "click .save":"savePerson"
},

savePerson: function(){
    this.model.set({
        name: this.$("input[name='name']").val(),
        age: this.$("input[name='age']").val(),
        address: this.$("input[name='address']").val()
    });
    this.model.save();
}

Otherwise, if you have many persons in the same template/view instance (not nice), just catch the current person's id `var personId = this.$("#"+this.model.id)`, to use this `personId` inside selectors above.

PS: I use `<%-value%>` instead of `<%=value%>` to interpolate this value, and have it be HTML-escaped.

Problem

I am using Backbone.js to display a list of people and their data. Every person has it's own `<div>`. The div is generated by `_.template` and contains `<input>` fields to display the person's data so it can be adjusted. There is also a button with `class=".save"`. In my view I have a function bound to the click of this button. I am looking for the best approach to get the values of the `<input>`-tags in the `div` belonging to the model. Here is my approach but I'm wondering if there's a better one. In my template I have dyanmically assigned ID's for the DOM elements based on the ID of the model. I use the same logic to find back the element in the view. TEMPLATE ``` <input value="<%=name%>" id="name_<%=id%>"/> <input value="<%=age%>" id="age_<%=id%>"/> <input value="<%=address%>" id="address_<%=id%>"/> <button class=".save">Save</button> ``` VIEW ``` events:{ "click .save":"savePerson" }, savePerson: function(){ this.model.set({ name: $("#name" + this.model.id).val(), address: $("#address_" + this.model.id).val(), age: $("#age_" + this.model.id).val() }); this.model.save(); } ```

Original source