gpt4 book ai didi

javascript - meteor JS : Routing with Backbone. js

转载 作者:搜寻专家 更新时间:2023-10-31 23:49:34 25 4
gpt4 key购买 nike

我正在尝试在我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com