javascript 单击或按 Enter 时触发 Backbone 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20366768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Backbone event firing on click OR press enter
提问by Melbourne2991
I am new to backbone and I am looking for a way for my button to be triggered when I press Enteras well as clicking. Currently showPrompt only executes on a click. What is the cleanest DRYest way to have it execute on pressing Enteras well, preferably only for that input field.
我是主干的新手,我正在寻找一种方法,当我按下Enter和点击时触发我的按钮。当前 showPrompt 仅在单击时执行。让它在按下时执行的最干净的 DRYest 方法是什么Enter,最好仅用于该输入字段。
(function () {
var Friend = Backbone.Model.extend({
name: null
});
var Friends = Backbone.Collection.extend({
initialize: function (models, options) {
this.bind("add", options.view.addFriendLi);
}
});
var AppView = Backbone.View.extend({
el: $("body"),
initialize: function() {
this.friends = new Friends(null, {view: this});
},
events: {
"click #add-friend": "showPrompt",
},
showPrompt: function () {
var friend_name = $("#friend-name").val()
var friend_model = new Friend({ name:friend_name });
this.friends.add( friend_model );
},
addFriendLi: function (model) {
$("#friends-list").append("<li>" + model.get('name') + "</li>");
}
});
var appView = new AppView;
}());
Also where can I read more about this kind of event binding? Do backbone events differ from JS or jQuery events in how they're defined?
另外我在哪里可以阅读更多关于这种事件绑定的信息?骨干事件与 JS 或 jQuery 事件的定义方式不同吗?
回答by Daniel Aranda
Assuming that you are using jQuery
for DOM manipulation
, you can create your own "tiny" plugin that fires the Enterevent in the inputs. Put it in your plugins.js
or whatever setup scripts file you have:
假设您正在使用jQuery
for DOM manipulation
,您可以创建自己的“小”插件来触发Enter输入中的事件。将它放在您plugins.js
或您拥有的任何安装脚本文件中:
$('input').keyup(function(e){
if(e.keyCode == 13){
$(this).trigger('enter');
}
});
Now that you have created this "enter" plugin, you can listen to enter events this way:
现在您已经创建了这个“输入”插件,您可以通过以下方式监听输入事件:
events: {
"click #add-friend": "showPrompt",
"enter #friend-name": "showPrompt"
}
回答by Niranjan Borawake
You can add one more event
to your events
hash in AppView
.
您可以更添加一个event
到您的events
哈希AppView
。
events: {
"click #add-friend": "showPrompt",
"keyup #input-field-id" : "keyPressEventHandler"
}
Where #input-field-id
is the one you want to add event on.
#input-field-id
您要在其上添加事件的那个在哪里。
Then add eventHandler
in AppView
.
然后加eventHandler
在AppView
。
keyPressEventHandler : function(event){
if(event.keyCode == 13){
this.$("#add-friend").click();
}
}
NOTE : This code is not tested but you can think doing it in this way.
注意:此代码未经测试,但您可以考虑以这种方式进行。
Have a look at thisto understand how Backbone
handles events
in a View
.
看看这个了解如何Backbone
把手events
的View
。