I have these event handlers for my template:
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 = '';
}
}
})
As you can see, the 'submit form'
and the 'keypress .addScore'
both have almost similar functions (ie adding a new collection to the database). My question is, is there a way that I can make a single function that can be passed to both event handlers? I am new to Meteor and I am just practicing the online tutorial I saw, hoping to modify it as I see fit. Thanks for the help! :D
You can create a function and call it inside the events
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 = '';
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.