I am very new to Meteor.
I am publishing users from the server with
Meteor.publish("users", function () {
return Meteor.users.find({}, {fields: {emails: 1, profile: 1, createdAt: 1}, sort: {createdAt: -1}});
});
I am routing to a user profile with iron-router
:
this.route('userProfile', {
path: '/users/:_id',
template: 'userProfile',
waitOn: function() {
return Meteor.subscribe('users', this.params._id);
},
data: function() {
return Meteor.users.findOne({_id: this.params._id});
},
});
I want to be able to show and edit profile name on this page. How can I best obtain this?
In my template I am showing the name with
<template name="userProfile">
<h1>{{#if profile.name}}{{profile.name}}{{else}}No Name{{/if}}</h1>
</template>
but the object has no name yet. I guess I can make the header clickable with
Template.userProfile.events({
'click h1': function(e) {
// change <h1> to <input type="text">
}
});
but I'm not sure what to do now.
Besides, is it a good idea to start using meteor-autoform
?
I find toggling between an input and an h1 is kind of painful so I can up with another solution (The trick here is to use a hidden span to measure the width of the text so that you can resize your input at each keypress).
Template:
<template name="userProfile">
<div>
<input class="js-profile-name" value="{{profile.name}}" />
<span class="js-profile-name-holder">{{profile.name}}</span>
</div>
</template>
Style:
.js-profile-name {
/* we style our input so that it looks the same as a H1 */
line-height: 1;
font-size: 24px;
outline: none;
border: 0;
}
.js-profile-name-holder {
position: absolute;
left: -9999px;
padding: 20px;
font-size: 24px;
}
JS:
Template.userProfile.onRendered(function () {
this.find('.js-profile-name').style.width = this.find('.js-profile-name-holder').offsetWidth + 'px';
});
Template.userProfile.events({
'change .js-profile-name': function (e, tmpl) {
if (!e.target.value) {
// prevent empty values
tmpl.find('.js-profile-name-holder').innerHTML = this.profile.name;
e.target.value = this.profile.name;
e.target.style.width = tmpl.find('.js-profile-name-holder').offsetWidth + 'px';
return;
}
Meteor.users.update({_id: this._id}, {
$set: {
'profile.name': e.target.value
}
});
},
'keypress .js-profile-name': function (e, tmpl) {
// resize our input at each keypress so that it fits the text
tmpl.find('.js-profile-name-holder').innerHTML = e.target.value;
e.target.style.width = tmpl.find('.js-profile-name-holder').offsetWidth + 'px';
}
});
I recognize this is quiet a bit of code for a single field, but it could easily be wrapped in a block helper and made reusable.
Template.userProfile.helpers({
/*here you can load individual user data*/
});
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.