Backbone.js 集合不应用模型(使用 Code Igniter)
我正在尝试使用 CodeIgniter 和 Backbone.js 开发一个网站,但在尝试将模型设置为我调用了 fetch() 的集合时遇到了问题。我正在使用 Phil Sturgeon 的 REST API,并且在集合上使用 fetch() 时收到 JSON 响应,但没有向其中添加子模型。
这是我正在使用的 javascript:
$(document).ready(function() {
window.Person = Backbone.Model.extend({});
window.People = Backbone.Collection.extend({
model: Person,
url: "/api/content/users/format/json"
});
});
和我的 CI 控制器:
require APPPATH.'/libraries/REST_Controller.php';
class Content extends REST_Controller {
function users_get() {
$users = array(
array('id' => 1, 'name' => 'Some Guy', 'email' => '[email protected]'),
array('id' => 2, 'name' => 'Person Face', 'email' => '[email protected]')
);
if($users) {
$this->response($users, 200); // 200 being the HTTP response code
} else {
$this->response(array('error' => 'Couldn\'t find any users!'), 404);
}
}
}
当尝试通过控制台 fetch() 集合的模型时,如下所示:
peoples = new People();
peoples.fetch();
peoples.models;
它获取 JSON 响应,但仍然显示“没有子对象”(参见图片) :
https://i.sstatic.net/e5vZv.png
知道出了什么问题吗?彻底难住了!
I'm attempting to develop a site using CodeIgniter and Backbone.js, but I'm running into an issue when attempting to set Models to a Collection I have called fetch() on. I am using the REST API by Phil Sturgeon, and am receiving a JSON response when using fetch() on the Collection, but no children Models are added to it.
Here's the javascript I'm using:
$(document).ready(function() {
window.Person = Backbone.Model.extend({});
window.People = Backbone.Collection.extend({
model: Person,
url: "/api/content/users/format/json"
});
});
And my CI Controller:
require APPPATH.'/libraries/REST_Controller.php';
class Content extends REST_Controller {
function users_get() {
$users = array(
array('id' => 1, 'name' => 'Some Guy', 'email' => '[email protected]'),
array('id' => 2, 'name' => 'Person Face', 'email' => '[email protected]')
);
if($users) {
$this->response($users, 200); // 200 being the HTTP response code
} else {
$this->response(array('error' => 'Couldn\'t find any users!'), 404);
}
}
}
And when attempting to fetch() the Models for the Collection via the console like:
peoples = new People();
peoples.fetch();
peoples.models;
It gets the JSON response, but still says 'There are no child objects' (see image):
https://i.sstatic.net/e5vZv.png
Any idea what is going wrong? Totally stumped!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
说明
在 fetch() 调用之后,直接
people.models
为空是正常的,您需要等待 ajax 请求结束。事实上,
fetch()
是异步,并且 Backbone JS 文档说:来源:http://documentcloud.github.com/backbone/#Collection-fetch
解决方案
您需要使用:
Explications
It's normal that
people.models
is empty directly after the fetch() call, you need to wait the end of the ajax request.Indeed,
fetch()
is asynchronous and the Backbone JS documention says :Source: http://documentcloud.github.com/backbone/#Collection-fetch
Solution
You need to use :