javascript - Backbone.js getting target attribute -
i trying figure out why value of e.target.getattribute('data-text') becoming null when go html backbone js file.
html:
<script type="text/template" id="lesson-template"> <span id="lesson-title"><%= tracks[0].title %></span> <select class="sel"> <% _.each(tracks, function(track) { %> <option value = "<%= track.text %>" data-text="<%= track.title %>"><%= track.title %></option> <% }); %> </select> <p id="tracktext"><%= tracks[0].text %></p> </script>
js:
window.librarylessonview = lessonview.extend({ events: { "change .sel " : "changetext" }, changetext: function(e) { alert(e.target.getattribute('data-text')); //i getting null value here! document.getelementbyid("lesson-title").innerhtml= e.target.getattribute('data-text'); //i getting null value here document.getelementbyid("tracktext").innerhtml= e.target.value; }
any clarification or appreciated!!
the change event fired on <select>
, not on <option>
, data attributes on <option>
s. dig through $(e.currenttarget)
(the <select>
) find appropriate <option>
, extract data attributes there or use have.
i have in template:
<select class="sel"> <% _.each(tracks, function(track) { %> <option value="<%= track.id %>"><%= track.title %></option> <% }); %> </select>
no data attributes @ all, unique track identifier <option>
's value. when change event triggered, can grab track id with:
var id = $(e.currenttarget).val(); // or $(e.target).val() currenttarget bit safer
you should have track list attached view this.collection
can use get
grab model out of collection:
var track = this.collection.get(id);
if don't have id
s on models use cid
s backbone create or else unique , findwhere
instead of get
.
now have track
model in hand, can pull out values want in usual way:
this.$('#lesson-title').html(track.get('title')); this.$('#tracktext').html(track.get('text'));
note i've switch this.$
, that's backbone view function equivalent this.$el.find
, localizing selectors view habit.
Comments
Post a Comment