i backbone newbie , trying develop todo app.
i have main view list view , has subviews. - subview content can edited on double click , saved when enter key pressed. - similar todo example given in backbone github code.
var subview = backbone.view.extend({ tagname: "li", events: { "dblclick" : "show_edit_view", "blur .element" : "close_edit_view", "keypress .element" : "save_edit_view", "click button.remove" : "remove_question" }, initialize: function(){ this.render(); this.listento(this.model, "change", this.render); }, render: function(){ this.$el.html(_.template($("#sub_view_template").html(),this.model.tojson())); return this; }, show_edit_view: function() { this.$el.find("div.view").addclass("no_show"); this.$el.find("input").removeclass("no_show"); }, close_edit_view: function(){ this.$el.find("div.view").removeclass("no_show"); this.$el.find("input").addclass("no_show"); }, save_edit_view: function(e){ if (e.keycode == 13) { this.model.save({name: e.currenttarget.value}); this.close_edit_view(); } } });
and template
<script id="sub_view_template" type="text/x-template"> <div class="view"><%= name %></div> <input class="element no_show" value="<%= name %>" type="text" /> <button class="remove">remove</button> </script>
this 1 works fine, model updated in view , update post request sent server.
but, when change initialization , save_edit_view functions, first change event fired , not change events.
initialize: function(){ this.render(); this.listento(this.model, "change", this.render); this.input = this.$("input.element"); }, save_edit_view: function(e){ if (e.keycode == 13) { this.model.save({name: $(this.input).val()}); this.close_edit_view(); } }
i wondering problem be?
thanks help!!!
the problem referring 1 object. means when make assignment:
this.input = this.$('input.element'); // match current elements
.
you getting value exact object. after first change
, this.input
not same object contains new value, , fails save
model new value.
a demonstration may help:
console.log(this.$('input.element') != this.$('input.element')); // true
this why following work:
save_edit_view: function(e){ if (e.keycode == 13) { this.model.save({name: this.$('input.element').val()}); this.close_edit_view(); } }