【问题标题】:MeteorJS: Routing with Backbone.jsMeteorJS:使用 Backbone.js 进行路由
【发布时间】:2012-07-12 18:00:03
【问题描述】:

我正在尝试在我的 MeteorJS 应用程序中使用 BackboneJS 实现路由器。 当您调用 url 'localhost:3000/1' 我的路由器将 id '1' 存储在会话中。之后,我想从会话中获取 id 并在我的查询中使用它来从我的集合中选择一个对象。但是,每当我尝试在查询中使用会话属性时,它都会失败。所以我想知道是否有更好的方法来使用 MeteorJS 进行路由以及为什么我的查询失败。

test.js

Meteor.subscribe("test");

Test = new Meteor.Collection("test");

Session.set("id", null);

Template.hello.test = function () {
  var avg = 0, total = 0, cursor = Test.find(), count = cursor.count();
  cursor.forEach(function(e)
  {
    total += e.number;
  });
  avg = total / count;

  var session_id = Session.get("id");

  var test = Test.findOne({id: session_id}); //doesn't work
  if (test) {
    test.avg = avg;
  }

  return test;
}

//ROUTER
var TestRouter = Backbone.Router.extend({
  routes: {
    ":get_id":    "get_id" 
  },
  get_id: function (get_id) {
    Session.set("id", get_id);
    console.log(get_id);
  }
});

Router = new TestRouter;

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

test.html

<head>
  <title>test</title>
</head>

<body>
  {{> hello}}
</body>

<template name="hello">
  <h1>Hello World!</h1>
  {{#if test}}
    {{#with test}}
      ID: {{id}}  Name: {{name}}  AVG: {{avg}}
    {{/with}}
  {{/if}}
</template>

model.js

Test = new Meteor.Collection("test");

Test.remove({});

if (Test.find().count() < 1) 
{
    Test.insert({id: 1,
                 name: "test1",
                 number: 13});

    Test.insert({id: 2,
                 name: "test2",
                 number: 75});
}

Meteor.publish('test', function () {
  return Test.find();
});

【问题讨论】:

    标签: javascript node.js meteor backbone.js url-routing


    【解决方案1】:

    您可能会发现 Iron Router 感兴趣 - 它是特定于流星的并且“了解您的订阅、数据源并帮助您解决常见问题”:https://github.com/EventedMind/iron-router

    【讨论】:

      【解决方案2】:

      Jifeng 是对的,如果您只需要路由功能,那么 page.js 就足够了。

      我和季峰是一个团队。直到最近,我们才得出“Meteor 和 Backbone 在模型/集合和视图/模板中存在一些特征冲突”的结论。随着我们对 Meteor 和 Backbone 的理解越来越深入,这个结论需要重新评估。请参考我上次的实验代码BBCloneMail-on-Meteor:Derick Bailey 的 BBCloneMail 修改为在 Meteor 上运行。关键是实现一个 Backbone 存储插件来连接 Meteor 的集合。插件接线生效后,只需稍作修改即可。

      【讨论】:

        【解决方案3】:

        我调试了代码,发现集合中的 'id' 是一个整数,而 session_id 是一个字符串。你需要 parseInt 来转换 session_id。

        我用page.js做路由,是“TJ Holowaychuk”的优秀作品“Micro client-side routerinformed from the Express router”。

        我强烈建议这样做,因为 Meteor 和主干在模型/集合和视图/模板中存在一些特征冲突。

        【讨论】:

        • var test = Test.findOne({_id: session_id});和 var test = Test.findOne(session_id);不工作。但是我今天会尝试实现page.js。
        • 它适用于 'Session.set("id", parseInt(get_id))'。感谢您的帮助!
        猜你喜欢
        • 1970-01-01
        • 2013-01-24
        • 1970-01-01
        • 2011-10-22
        • 2012-02-19
        • 1970-01-01
        • 1970-01-01
        • 2012-08-04
        • 1970-01-01
        相关资源
        最近更新 更多