Get a DOM element from a template in spine mode

I use Backbone.js to display a list of people and their data.

Each person has a <div> . The div is generated by _.template and contains <input> fields for displaying human data so that it can be adjusted.

There is also a button with class=".save" . In my opinion, I have a function related to pressing this button. I am looking for the best approach to get <input> -tags in divs belonging to the model.

Here is my approach, but I wonder if there is any better . In my template, I assigned a Dyanmically ID for DOM elements based on the model identifier. I use the same logic to find an element in a 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(); } 
+4
source share
1 answer

If each person is a different instance of the view with its own template, you can simply define the scope of the selector for the view 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 people in the same instance / view instance (not nice), just catch the current person id var personId = this.$("#"+this.model.id) to use this personId selector above.

PS: I use <%-value%> instead of <%=value%> to interpolate this value and have it using HTML escaping.

+6
source

Source: https://habr.com/ru/post/1497418/


All Articles