例如,请考虑TodoMVC app。
我正在编写自己的应用版本。双击待办事项时,会显示一个输入字段。
当输入字段模糊时,我想保存更改。但是如果用户进行更改然后按下escape,我不想保存更改。
问题是按下输入字段上的转义键会触发模糊事件。因此,当我按下escape时,我有侦听转义键操作的函数运行...但是侦听模糊事件的函数也是如此。
如何在按下退出键时执行某些操作,而不是运行模糊事件功能?
视图/ todo.js
var app = app || {};
app.TodoView = Backbone.View.extend({
tagName: 'li',
className: 'list-group-item',
template: _.template( $('#todo-template').html() ),
render: function() {
this.$el.html( this.template(this.model.toJSON()) );
this.$el.find('.edit-mode').hide();
this.$el.find('.remove-todo').hide();
return this;
},
events: {
'click input[type="checkbox"]': 'check',
'mouseenter': 'showRemove',
'mouseleave': 'hideRemove',
'click .remove-todo': 'remove',
'dblclick .todo-title': 'showEditMode',
'keyup input.edit-todo': 'updateOnEnter',
'blur input.edit-todo': 'closeAndUpdate'
},
initialize: function() {
this.listenTo(this.model, 'change', this.render);
},
check: function(e) {
this.model.save({
completed: true
});
},
showRemove: function(e) {
$(e.currentTarget).find('.remove-todo').show();
},
hideRemove: function(e) {
$(e.currentTarget).find('.remove-todo').hide();
},
remove: function(e) {
var $el = $(e.currentTarget);
this.model.destroy({
success: function(model) {
app.todos.remove(model);
$el.closest('li').remove();
},
error: function() {
alert('Unable to remove todo.');
}
});
},
showEditMode: function(e) {
var $el = $(e.currentTarget);
var $editMode = $el.closest('li').find('.edit-mode');
$el.closest('.view-mode').hide();
$editMode.show();
$editMode.find('.edit-todo').focus();
},
updateOnEnter: function(e) {
if (e.which === 13) {
this.closeAndUpdate();
}
else if (e.which === 27) {
this.closeEditMode();
}
},
closeEditMode: function() {
var $input = this.$el.find('.edit-todo');
$input.closest('li').find('.view-mode').show();
$input.closest('.edit-mode').hide();
},
closeAndUpdate: function() {
var self = this;
var $input = this.$el.find('.edit-todo');
var newTitle = $input.val();
if (newTitle !== this.model.get('title')) {
this.model.save({
title: newTitle
}, {
success: function(model) {
self.closeEditMode();
},
error: function() {
alert('Unable to update todo');
}
});
}
else {
this.closeEditMode();
}
}
});
答案 0 :(得分:3)
按下Esc时,可以在keypress
处理程序中设置一些布尔标志,然后在blur
处理程序中检查它:
...
events: {
...
"keypress .edit" : "keypress",
"blur .edit" : "blur"
},
...
close: function() {
...
},
blur: function() {
if (!this.escFlag) this.close();
this.escFlag = false;
},
keypress: function(e) {
if (e.keyCode == 27) this.escFlag = true;
},
...