Meteor 0.8.0中的多页面应用程序没有Iron-Router或任何模块

时间:2014-03-30 01:56:08

标签: jquery html dom meteor iron-router

我的目标是从一个页面切换到另一个页面。虽然我知道如何使用Iron-Router进行此操作,但我想自己编程,因为我正在向有窗口的人教Meteor,因此没有Iron-Router。

编辑:SUB-QUESTION:这里提出的3种方法效率更高?

我的第一个方法:

//HTML
<body>
  {{>mainTemplate}}
</body>

//Cliente JS Initially
Session.set('current', 'initialTemplate')
Template.mainTemplate = function()
{
    return Template[Session.get('current')];
};

//Later
Session.set('current', 'someOtherTemplate')

这是一种非常流行的方式,但它需要大量未经IDE检查的手动字符串,并可能导致错误。所以我的第二种方法是解决这个问题:

//HTML
<body>
</body>

//JS Client Initially
UI.materialize( Template.initialTemplate, document.body );

//Later
$("body").html("");
UI.materialize( Template.someOtherTemplate, document.body );

第二种方法使用变量而不是字符串,它非常易读,更简单,更简单并且可以工作但是我对jQuery有点怀疑,我今天第一次使用它。另外,我不知道Meteor的内部是否真的很方便删除了大量的HTML。如果可能的话,我宁愿采用纯粹的流星法。

提前致谢。

修改 这个模式目前的工作就像一个魅力!有人能找到更简单的吗?

//HTML
<body>
  {{>mainTemplate}}
</body>

//JS Client Initially
var current = Template.initialTemplate;
var currentDep = new Deps.Dependency;

Template.mainTemplate = function()
{
  currentDep.depend();
  return current;
};

function setTemplate( newTemplate )
{
    current = newTemplate;
    currentDep.changed();
};

//Later
setTemplate( Template.someOtherTemplate );

此模式取自answer中的此Meteor docs和此部分。

2 个答案:

答案 0 :(得分:1)

我为一个只有六页的应用程序解决了这个问题,其中添加Iron Router感觉有点过分。我是这样构建的:

<body>
{{> root}}
</body>

<template name="root">
  {{#if currentPageIs "home"}}
    {{> home}}
  {{/if}}
  {{#if currentPageIs "about"}}
    {{> about}}
  {{/if}}
  {{! etc. }}
</template>

然后你定义一个Session变量currentPage,在我的例子中可以是homeabout或其他四个页面名称;并单击链接或按钮来更改页面实际上只更新了Session变量。然后这个“穷人的路由器”的助手看起来像这样:

Template.root.currentPageIs = function (page) {
  return Session.equals("currentPage", page);
};

就是这样。没有jQuery,没有使用模板作为字符串(我认为应该使用新的模板引擎打破Meteor 0.8)。它完全是流星雨。显然,只有少数页面/路线,这种方法变得相当繁琐;但是它不需要包装,而且对于流星新手来说非常清楚。

为了完整性,这是一个示例页面和更改页面的帮助程序:

<template name="home">
  <p>Welcome to our website! You can learn more
  <a href="#" id="goToAbout">about us</a>.</p>
</template>

Template.home.events({
  "click #goToAbout": function (event, template) {
    event.preventDefault();
    Session.set("currentPage", "about");
  }
});

答案 1 :(得分:1)

我还没试过,但根据你上面的代码,我觉得这样可行:

//HTML
<body>
  {{>mainTemplate}}
</body>

//Cliente JS Initially
var current = Template.initialTemplate;
var currentDep = new Deps.Dependency;

Template.mainTemplate = function()
{
  currentDep.depend();
  return current;
};

//Later
current = Template.someOtherTemplate;
currentDep.changed();

这只是基于您的“理想”解决方案,但希望将会话变量限制转换为具有EJSON功能的值。