2016-10-11 17 views
0

[編輯]我使用流星保存當前用戶的價值在HTML中使用它

大家好,

我已經搜索並嘗試了很多東西,但我不能做我想做的。 我正在做一個教程做一個ToDo列表,當你檢查一個任務時,我想把檢查任務的用戶的名字。

<template name="task"> 
     <li class="{{#if checked}}checked{{/if}}">{{#if checked}}<!-- the name of the user who checked it -->{{/if}} 
    <!-- the rest isn't useful for my question --> 

我試着{{currentUser.username}}但是當我登錄了別人的名字改變...

還有就是JS事件處理程序

'click .toggle-checked'() { 
    // Set the checked property to the opposite of its current value 
    Meteor.call('tasks.setChecked', this._id, !this.checked); 
    } 

而且方法調用

'tasks.setChecked'(taskId, setChecked) { 
    check(taskId, String); 
    check(setChecked, Boolean); 
    Tasks.update(taskId, { $set: { checked: setChecked } }); 
    } 

的JS感謝您的幫助

回答

1

如果您使用{{currentUser.username}},您將始終擁有登錄用戶的數據。

爲了得到你想要的,你需要註冊誰在你的方法檢查任務的用戶的_id

'tasks.setChecked'(taskId, setChecked) { 
    check(taskId, String); 
    check(setChecked, Boolean); 

    // Check that 'setChecked' is true and that the user is logged in, 
    // Otherwise just update the status 
    if (setChecked && this.userId) { 
    Tasks.update(taskId, { 
     $set: { 
     checked: setChecked, 
     userId: this.userId, 
     } 
    }); 
    } else { 
    Tasks.update(taskId, { 
     $set: { 
     checked: setChecked, 
     } 
    }); 
    } 
} 

請務必相應地更新您的模式,如果你正在使用一個。

在你的模板

然後,檢索用戶數據並顯示它:

// file task.js 
import './task.html'; 

Template.task.helpers({ 
    checkerUser() { 
    // The template data are those of the current task, check if userId is defined and task is checked 
    const { userId, checked } = Template.currentData(); 
    /* Or you can do 
    * const userId = Template.currentData().userId; 
    * checked = Template.currentData().checked; 
    */ 
    if (userId && checked) { 
     return Meteor.users.findOne({ _id: userId }).profile.username; 
    } 
    return null; 
    } 
}); 

Template.task.events({ 
    'click .toggle-checked'() { 
    // Set the checked property to the opposite of its current value 
    Meteor.call('tasks.setChecked', this._id, !this.checked); 
    } 
}) 

最後,在HTML:

// file task.html 
<template name="task"> 
    <li class="{{#if checked}}checked{{/if}}"> 
    {{#if checkerUser}}Completed by {{checkerUser}}{{/if}} 
    </li> 
</template> 

從技術上說,你的方法,你還需要檢查更加部門的不同的情況。例如,當您取消選中任務時,應從記錄中刪除userId,以便如果未登錄的用戶再次檢查該名稱,該名稱將不是第一個用戶的名稱(或者,如果用戶,則可以爲$unset userId沒有登錄時設置checked = true

+0

嗨,謝謝你的所有解決方案和意見:),它只填寫完了,但沒有添加名稱,我認爲這是因爲我有一個名爲task.js的文件誰包含一個Template.task.events,所以我不知道我可以把你做的幫手放在哪裏......你有個想法嗎?我試圖做一個其他文件並導入所有的東西,但它沒有把檢查任務的人的名字......你能幫我嗎? – Jerome

+0

[編輯]我想我不能顯示這個名字,因爲我真的不知道如何打電話給助手... – Jerome

+0

所以是的,我已經嘗試了很多東西,問題是我從來沒有去過checkerUser(),我不知道如何調用「去checkerUser()」,因爲這是爲什麼助手的調用{{checkerUser}}不是? – Jerome

相關問題