我正在Backbone.js中创建一个小项目,并且正在运行一个json-server
程序包以将其填充一些数据。我db.json
用数据制作了一个文件并运行json-server --watch db.json
,它可以在上完美地运行localhost:3000
。在我的Backbone应用程序中,我有以下内容:
// app/javascripts/collections/resumes.js
define(['backbone', 'models/resume'], function (Backbone, Resume) {
var ResumesCollection = Backbone.Collection.extend({
model: Resume,
url: 'http://localhost:3000/resumes'
});
return ResumesCollection;
});
// app/javascripts/views/resumes/resume.js
define(['backbone', 'jquery'], function (Backbone, $) {
var ResumeView = Backbone.View.extend({
tagName: 'article',
render: function () {
this.$el.html(this.model.get("firstName"));
return this;
}
});
return ResumeView;
});
// app/javascripts/views/resumes/index.js
define(['backbone', 'views/resumes/resume'], function (Backbone, ResumeView) {
var ResumesList = Backbone.View.extend({
tagName: 'section',
initialize: function() {
this.collection.fetch();
},
render: function() {
var resumesView = this.collection.map(function (cv) {
return new ResumeView({model: cv}).render().el;
});
this.$el.html(resumesView);
return this;
}
});
return ResumeList;
});
这是我的app/router.js
:
define(['backbone',
'collections/resumes',
'views/resumes/resume',
'views/resumes/index'],
function (Backbone, ResumesCollection, ResumeView, ResumeList) {
var AppRouter = Backbone.Router.extend({
routes: {
'resumes': 'showAll'
},
showAll: function () {
this.ResumeList.render();
}
});
return AppRouter;
});
并且app/javascripts/main.js
我有这个:
require.config({
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: [
'underscore',
'jquery'
],
exports: 'Backbone'
}
},
paths: {
jquery: '../node_modules/jquery/dist/jquery',
underscore: '../node_modules/underscore/underscore',
backbone: '../node_modules/backbone/backbone'
}
});
require(['backbone',
'jquery',
'router'
], function (Backbone, $, AppRouter) {
var Router = new AppRouter();
Backbone.history.start({
pushState: true,
root: '/'
});
});
此外,我用咕嘟咕嘟上运行开发服务器localhost:8080
通过gulp-connect
和gulp-livereload
。但是,当我导航到时localhost:8080/resumes
,它将返回我Cannot GET /resumes
,尽管控制台中没有错误。我在做什么错?+
通过所提供的内容,我们无法查明确切的问题和原因,但是无论如何我还是要尝试提供帮助。
我尝试了json-server,并使用以下命令启动了它db.json
:
{
"posts": [{
"id": 1,
"title": "json-server",
"author": "typicode"
}, {
"id": 2,
"title": "This is a test",
"author": "Emile Bergeron"
}]
}
然后,我制作了最简单的收藏夹来使用它。
var PostCollection = Backbone.Collection.extend({
url: "http://localhost:3000/posts"
});
var posts = new PostCollection();
posts.fetch({
success: function(){
console.log(posts.pluck('title'));
}
});
在控制台中,我可以看到:
["json-server", "This is a test"]
使用它非常简单!因此问题出在其他地方。也许向我们显示完整的请求(原始数据)。
this.collection.fetch(); // this is enough
没必要通过,{ data: { fetch: true, type:"get" } }
因为它仍然是默认行为。
内部的以下行将ResumeList
失败:
return new ResumeView({model: cv}).render().el;
这是因为的render
功能ResumeView
不会返回this
。
总体而言,您的代码看起来不错。
如果要将API放置在另一台服务器(即另一台域)上,请查看CORS,这将使js能够获取其他域。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句