我在我的网站的一个页面上开发了一个非常简单的Backbone应用程序,并且遇到了表单问题。
我有一个列表(项目集合),当我点击一个项目的名称时,它被一个表单替换。
当我编辑名称并按回车它工作正常,但我找不到解决方案: - 如果我按“esc”键或更好,在页面上的任何其他地方逃避表格 - 当我按Enter键保存我的项目,当我没有修改文字。
现在,当我点击一个项目并加载表单时,我被迫更改名称,如果我想退出for,请按Enter键。
这是我的编辑形式Backbone视图:
var EditForm = Backbone.View.extend({ model: Item, template: _.template('<form>' + '<input name=name value="<%= name %>" />' + '</form>'), events: { submit: 'save' }, save: function(e){ e.preventDefault(); var newName = this.$('input[name=name]').val(); this.model.set({name: newName}); this.model.save(); }, render: function(){ this.$el.html(this.template(this.model.attributes)); return this; } });如果有人已经实现了我会非常感谢有一个例子。
谢谢
I have developped a very simple Backbone app on one page of my website and having issues with forms.
I have a list (collection of items) and when I click on the name of an item, it is replaced by a form.
When i edit the name and press enter it works fine, but I don't find the solution to: - escape the form if I press "esc" key or better, anywhere else on the page - save my item when i press enter, when I did not modify the text.
Right now, when I click on an item and load the form, I am forced to change the name and press enter if I want to exit the for.
Here is my edit form Backbone view:
var EditForm = Backbone.View.extend({ model: Item, template: _.template('<form>' + '<input name=name value="<%= name %>" />' + '</form>'), events: { submit: 'save' }, save: function(e){ e.preventDefault(); var newName = this.$('input[name=name]').val(); this.model.set({name: newName}); this.model.save(); }, render: function(){ this.$el.html(this.template(this.model.attributes)); return this; } });If anyone already implemented that I would be very thankful to have an example.
Thank you
最满意答案
您需要在视图上有一个“keyup”处理程序,并检查其处理程序中的键代码。 类似于以下内容:
//modify your events object like this events:{ submit: "save", "keyup": "checkAndHandleCancel" } //handler checkAndHandleCancel: function(e){ if (e.keyCode == 27) { //handle your cancel action here } }请记住,这只有在重点放在表单上才有效。 如果需要处理全局“取消”,则需要在文档上使用类似的“keyup”处理程序,然后将该事件传播到视图中。
You need to have a "keyup" handler on your view and check the keycode in its handler. Something like the following :
//modify your events object like this events:{ submit: "save", "keyup": "checkAndHandleCancel" } //handler checkAndHandleCancel: function(e){ if (e.keyCode == 27) { //handle your cancel action here } }Please keep in mind that this would only work if the focus is on the form. If you need to handle a global "cancel", you'd need to have a similar "keyup" handler on the document and then propagate that event to your view.
更多推荐
发布评论