问题
I found example code to fetch values of text inputs from a submitted form in Meteor. I wrote my own version. Works great! Here's a snippet from my form submit event handler:
'submit form': function(event, template) {
event.preventDefault();
Assets.insert({
name: event.target.inputName.value,
location: event.target.inputLocation.value,
value: event.target.inputValue.value
});
}
- I'm confused about event.target.playerName. What kind of object is it? Does Meteor set up that object for us? Or is this a jQuery thing? Or something else?
- Is it any better/safer to use event.currentTarget? Sounds like nesting forms is not allowed, so it might not make any difference since there wouldn't be any way for it to "bubble up" given the 'submit form' event map key.
Crossposted here.
回答1:
In that case, you're not using the template
object but rather the plain jQ way. From a quick look at the page containing the example code, they use function(event)
as opposed to function(event, template)
(I prefer the latter, but that's a matter of taste). Here's how t make use of the template
object.
Suppose your form look like this
<template name='createAccount'>
<form role="form">
<input placeholder="Your Name" name="name" type="text" />
<input placeholder="E-Mail Address" name="email" type="email" />
<input placeholder="Password" name="password" type="password" />
<div id="submitForm" class="outerButton">
(SOME BUTTON)
</div>
</form>
</template>
Here's pattern using template
:
Template.createAccount.events({
'click #submitForm': function (event, template) {
var displayName = template.find("input[name=name]").value;
var eMailAddress = template.find("input[name=email]").value;
var password = template.find("input[name=password]").value;
< INSERT displayName, eMailAddress, password IN COLLECTION>
}
})
回答2:
Pretty new to meteor myself so I could be completely wrong, but I believe your event target is just standard javascript, not meteor or jquery specific. I've been thinking of it as a shorthand for creating your own object.addEventListener()
, so your playerName
is going to be a child element of the form since it's the key of the object.
Imagine if it was setup something like form.addEventListnener('submit', function(e){ ... })
maybe makes it more familiar.
As for number 2, I wouldn't see why you couldn't use currentTarget if you needed to. I don't think it'd be any safer unless you really didn't know where the event might be coming from (perhaps creating a custom package?).
回答3:
event.target
returns the DOM element. In your case, it's theform
element, and you can use named property to get its node, see the specIn this case it's OK to use either target or currentTarget. In other examples when there is a 'nested' node, it might be better to use currentTarget.
来源:https://stackoverflow.com/questions/27198927/how-does-event-currenttarget-input-value-give-me-an-input-value-in-a-meteor-fo