gpt4 book ai didi

json - Backbone.js + REST

转载 作者:行者123 更新时间:2023-12-04 05:33:54 27 4
gpt4 key购买 nike

我对 Backbone.js 非常陌生,并且一直在关注几个教程来提出下面的脚本。我想要实现的是在使用我的路由时从 rest api 检索 JSON 数据。如果您查看 friend 路线的人员功能,您可以看到我要去哪里。我哪里出错了?

<!DOCTYPE html>
<html>
<head>
<title>I have a back bone</title>
</head>
<body>
<button id="add-friend">Add Friend</button>
<ul id="friends-list">
</ul>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
<script>
Friend = Backbone.Model.extend({
name: null,
age: null,
});
FriendDetailModel = Backbone.Model.extend();
FriendDetailCollection = Backbone.Collection.extend({
url: 'slim/index.php/friends/',
model: FriendDetailModel

});

Friends = Backbone.Collection.extend({
initialize: function(models, options) {
this.bind("add",options.view.addFriendLi);
}
});
AppView = Backbone.View.extend({
el: $("body"),
initialize: function() {
this.friends= new Friends(null, {view:this});
},
events: {
"click #add-friend": "showPrompt",
},
showPrompt: function () {
var friend_name = prompt("Who is your friend?");
var friend_age = prompt("What is your friends age?");
var friend_model = new Friend({name: friend_name, age: friend_age});

this.friends.add(friend_model);
},
addFriendLi: function(model) {
$("#friends-list").append("<li>" + model.get('name') + " " + model.get('age') + "</li>");
}
});
var appview = new AppView;

AppRouter = Backbone.Router.extend({
routes: {
"friends":"people",
"person/:name":"personDetail"
},

people: function() {
console.log('all the people');
var people = new FriendDetailCollection;
people.fetch({
success: function(data) {
console.log(data);
}

},

personDetail: function(name) {
console.log('one person named ' + name);
}
});

var approuter = new AppRouter;
Backbone.history.start();
</script>
</body>
</html>

运行 people.fetch Console.log 后显示
d
_byCid: Object
_byId: Object
length: 4
models: Array[4]
__proto__: x

如果我做 console.log(data.toJSON());它返回
[]

最佳答案

我最终通过执行以下操作解决了问题:

我在路由器之外创建了一个新集合:

var people = new FriendDetailCollection;

当我创建 View 时,我指定了我之前创建的集合。
friendview = new FriendView({collection: people});

我在 FriendView 中有一个错字。以前我有 _.bind(this, 'render')。它必须是
_.bindAll(this,'render');

此外,我将我的 console.log 放在我的 FriendView 中的 render() 函数中。
FriendView = Backbone.View.extend({
el: $("body"),
initialize: function() {
_.bindAll(this,'render');
this.collection.bind('reset', this.render);
},
render: function() {
console.log(this.collection.toJSON());
}

});

关于json - Backbone.js + REST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12224211/

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