我的模板有这些事件处理程序:
Template.addPlayerForm.events({
'submit form': function(e) {
e.preventDefault();
var playerName = e.target.playerName.value;
var playerScore = e.target.playerScore.value;
if (playerName !== "" && playerScore !== "") {
Meteor.call('createPlayer',playerName,playerScore);
e.target.playerName.value = '';
e.target.playerScore.value = '';
}
},
'keypress .addScore': function(e) {
if (e.which >= 48 && e.which <= 57) {
return e.charCode;
}
else if (e.which === 13 || e.keycode === 13) {
e.preventDefault();
var playerName = e.target.playerName.value;
var playerScore = e.target.playerScore.value;
if (playerName !== "" && playerScore !== "") {
Meteor.call('createPlayer',playerName,playerScore);
e.target.playerName.value = '';
e.target.playerScore.value = '';
}
}
})
如您所见,'submit form'
和'keypress .addScore'
两者具有几乎相似的功能(即向数据库添加新集合)。我的问题是,有没有办法可以将一个函数传递给两个事件处理程序?我是Meteor的新手,我正在练习我看到的在线教程,希望能够按照我认为合适的方式对其进行修改。谢谢您的帮助! :d
答案 0 :(得分:2)
您可以创建一个函数并在事件
中调用它Template.addPlayerForm.events({
'submit form': function(e) {
funcName(e)
},
'keypress .addScore': function(e) {
if (e.which >= 48 && e.which <= 57) {
return e.charCode;
}
else if (e.which === 13 || e.keycode === 13) {
funcName(e)
}
}
})
funcName = function(e){
e.preventDefault();
var playerName = e.target.playerName.value;
var playerScore = e.target.playerScore.value;
if (playerName !== "" && playerScore !== "") {
Meteor.call('createPlayer',playerName,playerScore);
e.target.playerName.value = '';
e.target.playerScore.value = '';
}
}