【问题标题】:Adding requested data to a collection using backbone.marionette使用backbone.marionette将请求的数据添加到集合中
【发布时间】:2014-03-19 17:26:33
【问题描述】:

在我的主干模型中,我试图向服务器发出请求以从一些 JSON 填充集合:

{
"accountType":["Full","Trial"]
}

在我的 account.js 模型中,我有:

accountManager.module("Entities", function(Entities, accountManager,Backbone, Marionette, $, _){

Entities.account = Backbone.Model.extend({});

Entities.accountCollection = Backbone.Collection.extend({
model: Entities.account,
comparator: "account",
url:"webapp/jsonData"
});


var API = {
getaccountEntities: function(){
var accounts = new Entities.accountCollection();
accounts.fetch();
if(accounts.length === 0){
console.log("No profiles loaded");
}
return accounts;
}};

accountManager.reqres.setHandler("account:entities", function(){
    return API.getaccountEntities();
});
});

Controller.js

accountManager.module("accountsApp.List", function(List, accountManager,Backbone, Marionette, $, _){

List.Controller = {
    listaccounts: function(){
        var accounts = accountManager.request("account:entities");
        var accountsListView = new List.accounts({
        collection: accounts});
        accountManager.mainRegion.show(accountsListView);
        }
    };
});

app.js

var profileManager = new Marionette.Application();

profileManager.addRegions({
 mainRegion: "#main-region",
});

 profileManager.on("initialize:after", function(){
 profileManager.profilesApp.List.Controller.listprofiles();
 });

如何使用返回的数据填充集合,然后将其显示在视图中?

按照我拥有的一本书中的教程进行操作,但似乎无法使其工作。

控制台记录错误(所以我知道它没有获取数据)并且我也收到错误:

'Uncaught ReferenceError: account is not defined'

有什么建议吗?

【问题讨论】:

  • 您的 API 返回什么?它是返回一个集合吗?从您上面的问题来看,您似乎正在尝试将模型提取到集合中。
  • 您好,感谢您的回复。我已经更新了我的问题,我正在关注持久数据部分,当我返回静态数据时它可以工作,但是当我尝试从服务器填充集合时,我遇到了问题。
  • 我已经从我的 app.js、account.js 和控制器中添加了代码。

标签: javascript jquery backbone.js marionette


【解决方案1】:

您正在尝试使用不返回集合的 API 端点来初始化集合。 “webapp/jsonData”需要返回类似

[
  { id: 1, name: "account 1", type: "Full"},
  { id: 2, name: "account 2", type: "Trial"},
  { id: 3, name: "account 3", type: "Full"}
]

请注意,它是一个对象数组,其中每个对象都将成为集合中的一个模型。

特别是,followign JSON(根据您的问题)无法创建集合:

{
  "accountType":["Full","Trial"]
}

相反,如果您想要一个帐户类型的集合,您的 JSON 需要类似于

[
  {name: "Full"},
  {name: "Trial"}
]

您的集合中还有一个小错误:comparator 值必须是对象属性。换句话说,它只有在每个帐户模型都有一个“帐户”属性时才有效。

【讨论】:

  • 哦,好的,我明白了,我有一个游戏集合,我将在此过程之后使用它,我必须解决其他问题来获取帐户类型并填充下拉列表,谢谢跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多