2014-10-09 61 views
1

例子:如果路由/模板不僅僅包含集合,而是如何從集合中獲取數據?

routes.js:

this.route("chapterPage", { 
    path: "/books/:bookId/chapters/:_id", 
    data: function() { 
    var chapter = Chapters.findOne(this.params._id); 
    var book = Books.findOne(this.params.bookId); 
    var chapters = Chapters.find({ 
     bookId: this.params.bookId 
    }, { 
     sort: { 
     position: 1 
     } 
    }); 
    return { 
     chapter: chapter, 
     book: book, 
     chapters: chapters 
    }; 
    } 
}); 

正如你可以看到這個模板/路由有兩個集合BookChapter。以前,我用單獨調用集合是這樣的:

chapter_form.js:

Template.chapterForm.events({ 
    "input #input-content": function() { 
    var currentChapter = Session.get("currentChapter"); 
    Chapters.update(currentChapter, { 
     $set: { 
     content: $("#input-content").html(); 
     } 
    }); 
    } 
}); 

但現在我的新航線/模板我不能這樣做,因爲它不是基於任何集合:

chapter_page.js:

Template.chapterPage.events({ 
    "input #input-content": function() { 
    console.log(chapter._id); // this returns is not defined 
    console.log(this._id); // this one too 
    } 
}); 

如何獲得AR回答這個?

編輯:

我也試過致電chapter_form.html模板:

<template name="chapterPage"> 
    {{> chapterForm}} 
</template> 

但它不顯示,顯示之類的東東:Cannot read property 'content' of undefined所以它是不承認的模板。

回答

1

你的代碼有兩個問題。

首先在data函數的chapterPage路由中,您不要return包含您的數據的對象。

// no return here in your question, need to do : 
return { 
    chapter: chapter, 
    book: book, 
    chapters: chapters 
}; 

然後在你的事件處理程序,您可以訪問使用this數據上下文,所以正確的語法來訪問章節或書籍ID this.chapter._idthis.book._id

編輯:

模板內的路線助手和事件處理程序,this是指分配給模板當前的數據上下文。

有幾種方法可以將數據上下文分配給模板。可以使用attribute="value"語法以及模板包含語法。

{{> myTemplate param1="value1" param2="value2"}} 

Template.myTemplate.helpers({ 
    paramsJoined:function(){ 
    return [this.param1,this.param2].join(","); 
    } 
}); 

您也可以使用父模板數據上下文來幫手值:

<template name="parent"> 
    {{> myTemplate someHelper}} 
</template> 

Template.parent.helpers({ 
    someHelper:function(){ 
    return { 
     param1:"value1", 
     param2:"value2" 
    }; 
    } 
}); 

如果使用模板包含語法,當你不指定數據上下文,它被認爲是從父數據上下文繼承。

您還可以使用{{UI.dynamic}}http://docs.meteor.com/#ui_dynamic)指定動態模板名稱以及動態數據上下文。

{{> UI.dynamic template=Router.template data=Router.data}} 

這是這種做法,iron:router使用動態設置路由模板的路由數據上下文(實現稍微複雜一些,雖然)。

流星提供實用程序訪問當前數據的上下文以及父數據的上下文,其可以是有益的:

http://docs.meteor.com/#template_currentdata

http://docs.meteor.com/#template_parentdata

+0

噢,對不起'return'是在實際的代碼。我意外刪除了它。 – alexchenco 2014-10-09 15:55:03

+0

這令人困惑,因爲我想知道你的模板如何在沒有它的情況下顯示任何感興趣的東西! – saimeunt 2014-10-09 15:56:05

+0

哦,謝謝它的工作。這幾周我一直在困惑。那麼這個''總是會引用當前的'路由'數據? – alexchenco 2014-10-09 15:57:29