编程语言
首页 > 编程语言> > javascript-MeteorJS:使用Backbone.js路由

javascript-MeteorJS:使用Backbone.js路由

作者:互联网

我正在尝试在MeteorJS应用中使用BackboneJS实现路由器.
当您呼叫网址“ 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();
});

解决方法:

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

我使用page.js进行路由,这是“ TJ Holowaychuk”的出色著作“受Express路由器启发的微型客户端路由器”.

我强烈建议这样做,因为流星和主干在Model / Collection&视图/模板.

标签:node-js,url-routing,meteor,backbone-js,javascript
来源: https://codeday.me/bug/20191201/2078009.html