试图从一个集合中获取一个特定的模型

时间:2012-08-18 20:39:42

标签: javascript jquery backbone.js underscore.js

我正在构建一个简单的backbone.js应用程序,而不使用“真正的数据库”。 我的数据库很简单,看起来像这样:

[
    { "Name": "Daniel", "Month": "abc", "year": "83" },
    { "Name": "Johan", "Month": "abg", "year": "33" }
]

我成功将数据提取到集合实例中,我做了console.log并看到它有效:

this.nameList = new NameList();
this.nameList.fetch();
console.log(this.nameList); 

在这里我很好,现在我尝试只使用该系列中的一个模型而没有任何效果。我试过了:

console.log(this.nameList.at(1));
console.log(this.nameList.get(id));  //when id is passed as a number.
console.log(this.nameList.getByCid(id))  //when id is passed as a number.

我总是得到“未定义”。

  • 我如何使用这样的简单数据库?
  • 我在哪里可以阅读这些内容?

作为更新,它在使用集合时适用于我:

    this.projectList = new ProjectList;
    this.projectList.fetch({
        success: function (data) {
            console.log(data.get(id));
        }
    });

使用单一模型时无效:

    this.project = new Project({id: id});
    this.project.fetch({
        success: function (data) {
            console.log(data);
        }
    });

现在我得到:GET ........ / Client / web / Data / projects / 3 404(Not Found)

为什么?

2 个答案:

答案 0 :(得分:0)

您可以从“models”属性中检索模型:

的console.log(this.nameList.models [0]。名称);

答案 1 :(得分:0)

/Client/web/Data/projects/3 404 (Not Found)

你确定你真的在RESTian位置提供服务吗?

集合的提取默认行为是在集合URL [/ Client / web / Data / projects]上执行GET,你说它正在提供正确的数据。

但是当您在单个模型上调用fetch()时,它会将该模型的id附加到集合URL:/ Client / web / Data / projects / 3,它将返回404 / Not Found响应。如果您手动尝试该URL,您实际上是否得到了响应?

至于为什么console.log(this.nameList.get(id))返回undefined,似乎没有正确填充nameList。看一下console.log(this.nameList.models)的输出 - 它实际上是否有您期望的模型?

相关问题