I am new to backbone and I am looking for a way for my button to be triggered when I press Enter as well as clicking. Currently showPrompt
only executes on a click. What is the cleanest DRYest way to have it execute on pressing Enter as well, preferably only for that input field.
(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;
}());
另外,我在哪里可以阅读有关此类事件绑定的更多信息?主干事件与 JS 或 jQuery 事件的定义方式有何不同?
Assuming that you are using jQuery
for DOM manipulation
, you can create your own "tiny" plugin that fires the Enter event in the inputs. Put it in your plugins.js
or whatever setup scripts file you have:
$('input').keyup(function(e){
if(e.keyCode == 13){
$(this).trigger('enter');
}
});
现在您已经创建了这个“enter”插件,您可以通过以下方式监听 Enter 事件:
events: {
"click #add-friend": "showPrompt",
"enter #friend-name": "showPrompt"
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)