3

我正在尝试使用 Meteor 创建一个博客应用程序。在这个博客中,有一个主页,访问者可以简单地阅读帖子,另一个部分是“管理”面板,我可以在其中编辑帖子。我正在尝试使用车把模板助手,但我不确定我哪里弄错了。我也是一名业余开发人员,并试图更好地学习 Meteor 框架。我的代码是这样的:

博客.html

<head>
  <title>Jeff Lam Tian Hung</title>
</head>

<body>
  <h1>Jeff Lam Tian Hung</h1>
  <a href="/" class="main">Main Page</a>
  <a href="/admin" class="admin">Admin</a>
  {{> content}}
</body>

<template name="content">
  {{#if currentPage "blog"}}
    {{#each posts}}
      <h2>{{Title}}</h2>
      <p>{{Body}}</p>
    {{/each}}
  {{/if}}

  {{#if currentPage "admin"}}
    <h2>{{admin}}</h2>
  {{/if}}
</template>

博客.js

// Declaration of Collections
Posts = new Meteor.Collection("Posts");

// Helper variable is for pages
// TODO: changing this var will change the
// page but now how to rerender the page?
var page = "blog";

// Declaration of Template Reactivity Variables
Template.content.currentPage = function (type) {
  return page === type;
};
Template.content.posts = function () {
  return Posts.find({}, {sort: {Date: 1}});
};
Template.content.admin = function () {
  return "This will render admin section";
};

// Router for Pages
var Router = Backbone.Router.extend({
  routes: {
    "":      "main",
    "admin": "admin"
  },
  main: function () {
    page = "blog";
  },
  admin: function () {
    page = "admin";
  }
});

var BlogRouter = new Router;

Meteor.startup(function () {
  Backbone.history.start({pushState: true});
});

publish.js(仅限服务器端代码)

Posts = new Meteor.Collection("Posts");

该页面将使用上述代码呈现博客文章,但是当我访问 localhost:3000/admin 时,页面变量设置为“admin”,但页面/模板不会重新呈现自身以显示“Admin” ' 文本。

但是,如果我设置 var page = 'admin' 并刷新应用程序,该页面会重新呈现管理消息就好了。我不确定我是否正确使用了车把模板助手来执行这种“带路由的单页模板刷新”。谢谢你的帮助!

4

1 回答 1

6

您的变量“页面”不是响应式的,只是一个普通的 JavaScript 变量。它无法通知 Meteor 的变化。

当我开始使用 Meteor 时,出于类似目的,我将页面“代码”放入 Session 变量中,这将触发您的页面更新。例如:

// Declaration of Template Reactivity Variables
Template.content.currentPage = function (type) {
    return Session.equals("page", type);
};

在你的路由器中:

...
Session.set("page", "admin");
…

(尽管您可能想将 Session.set 位放在它自己的函数中)

因为 Session 变量在 Meteor 框架中是响应式的,并且会在更改时通知。

于 2012-10-20T07:15:57.807 回答