javascript - meteor JS : Routing with Backbone. js

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

我正在尝试在我的 MeteorJS 应用程序中使用 BackboneJS 实现路由器。 当您调用 url 'localhost:3000/1' 时,我的路由器会在 session 中存储 ID '1'。之后我想从 session 中获取 id 并在我的查询中使用它来从我的集合中选择一个对象。但是每当我尝试在查询中使用 session 属性时,它都会失败。所以我想知道是否有更好的方法使用 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();
});

最佳答案

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

我使用 page.js用于路由,这是“受Express路由器启发的微型客户端路由器”,来自“TJ Holowaychuk”的优秀作品。

我强烈建议这样做,因为 Meteor 和 backbone 在 Model/Collection & View/Template 中有一些功能冲突。

关于javascript - meteor JS : Routing with Backbone. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11461097/

相关文章:

javascript - Node.js 中的 Get/create 操作中未发现错误

node.js - 依次执行node.js代码

meteor - 如何使用递归模板?

javascript - 使用 Meteor session 切换模板

mongodb - 设计 MongoDB 集合与关系方法

javascript - 如何更新数组对象的数组特定属性

javascript - 使用reactjs setState回调计算值获取先前的输入值

javascript - 想要禁用我的下一个按钮,直到使用 javascript 填充我的所有选项

javascript - 完整日历 : How to support one tap and no long tap

node.js - Sequelize 迁移重新创建表