2013-03-03 64 views
1

我在客戶端文件下列事件:this.userId是後不插入未定義的MongoDB的財產提交

Template.categories.events({ 
... 

    'keyup #add-category': function (e,t){ 
    if (e.which === 13) 
    { 
     var catVal = String(e.target.value || ""); 
     if (catVal) 
     { 
     lists.insert({Category:catVal,owner:this.userId}); 
     Session.set('adding_category', false); 
     } 
    } 
    }, 
    ... 
}); 

這是相關模板部分:

<template name="categories"> 
    <div id="categories" class="btn-group"> 
     {{#if new_cat}} 
     <div class="category"> 
      <input type="text" id="add-category" value="" /> 
     </div> 

     {{else}} 
     <div class="category btn btn-inverse" id="btnNewCat">&plus;</div> 
     {{/if}} 
     {{#each lists}} 
     <div class="category btn {{list_status}}" id="{{_id}}">  
      {{Category}} 
     </div> 
     {{/each}} 
    </div> 
</template> 

因此,當一個新的類別被插入,所有者應該被設置..但它不。

這裏是MongoDB中的條目:

> db.lists.find() 
{ "Category" : "test-admin", "_id" : "EsybjC3SLnNzCBx2t" } 

任何想法,我做錯了嗎? (其實我繼「入門流星」圖書借閱庫的例子

編輯看來:

console.log(this.userId); 
undefined 

回答

1

交換這一行:

lists.insert({Category:catVal,owner:this.userId}); 

這一個:

lists.insert({Category:catVal,owner:Meteor.userId()}); 
+0

繁榮。這本書是從寫這本書的時候開始改變的嗎?這仍然是當前登錄用戶? – 2013-03-03 15:05:12

+0

我不確定,如果上下文是'Meteor',那麼使用'this'就行。帳戶框架是非常近期的(2個月),書的寫法是什麼時候? 'Meteor.userId()'應該得到已登錄的用戶 – Akshat 2013-03-03 15:08:05

+0

我正在使用應用程序,'console.log(this.userId)'在我的事件中工作 – Prashant 2013-03-03 15:12:17

1

this可能不是你希望它是事件裏面有什麼你應該調試以確認情況是這樣的,你可能剛剛得到了this.userId的undefined,我建議將this賦值給這個事件處理函數以外的變量(稱爲「self」或「that」),但在this將會成爲你真正想要的東西,然後你可以引用這個變量e事件處理程序。

它應該是這樣的:

function thatRegistersEvents() { 
    var self = this; 

    // ... 

    registerSomeEvent(function() { 
     return self.someThisProperty; 
    }); 
} 
+0

謝謝,確實看起來this.userId是未定義的(+1),但我認爲這可能是由於如何在流星中設置帳戶/用戶的問題所引起的.. – 2013-03-03 15:01:45

0

這是正確的行爲。如果您閱讀官方流星文檔以參考this.UserId,則僅在Meteor.publish()Meteor.methods()中可用。 this.UserIdMeteor.template()中不可用,您在上面的代碼示例中完成了此操作,因此必須在模板中使用Meteor.userId()