在backbone.js中获取模型属性

7

我有这个模型

var Item = Backbone.Model.extend({
   url: 'http://localhost/InterprisePOS/Product/loaditembycategory/Event Materials'
});

var onSuccess = function(){ alert("success"); };

同时,还有一个集合

var Items = Backbone.Collection.extend({
    model: Item
});

以下是我的其余代码:

var item = new Item();
var items = new Items();
item.fetch({ success: onSuccess });
alert(items.get("ItemCode"));

我想要的是简单地获取模型的属性。现在我在firebug上看到了这个。当我在浏览器上运行它时,我会得到警告成功,下一个警告是未定义enter image description here
这是输出结果:
{"ErrorMessage":null,"Items":[{"ErrorMessage":null,"CategoryCode":"Event Materials","ClassCode":null,"Components":null,"GroupCode":null,"ImageURL":null,"ItemCode":"ITEM-123","ItemDescription":"Old World Lamppost\u000d\u000a\u000d\u000a","ItemName":"GET123","ItemType":null,"KitItem":null,"Matrix":null,"Prefix":null,"RetailPrice":107.990000,"SalesTaxCode":null,"UPCCode":null,"UnitMeasureCode":"EACH","UnitsInStock":0,"Value":null,"WholesalePrice":95.000000}]}

注意

那只是它返回的项目之一。我只发布了一个项目,以便不会太长。

2个回答

11

你正在对集合调用get方法(请参见http://documentcloud.github.com/backbone/#Collection-get)。

看起来你真正想要做的是对集合进行迭代,并在每个项上调用get方法。

items.each(function(item) {
  item.get('ItemCode');
});

如果没有,请详细说明!

此外,如果您的模型URL响应一个模型列表,则应该在Collection中定义url属性而不是在模型中定义。

var Items = Backbone.Collection.extend({
    model: Item,
    url: 'http://localhost/InterprisePOS/Product/loaditembycategory/Event Materials'
});
你的响应应该是一个数组,其中项目作为数组元素 [<item1>, <item2>, ...],而不是一个带有 {'Items': [<item1>, <item2>, ...] } 的 JSON 对象。如果你不想修改响应,你将不得不在你的集合上实现 parse 函数 (http://documentcloud.github.com/backbone/#Collection-parse)。
另外,正如 @chiborg 提到的那样,你在调用 fetch 后立即调用 get(它将异步完成),因此不能保证数据可用。
正确的解决方案是在集合上绑定一个“刷新”监听器。
items.on('refresh', function() {
  // now you have access to the updated collection
}, items);

抱歉关于模型部分的问题。我只是在进行实验,因为我注意到模型项没有获取属性,它是空的。还有关于解析的事情。我尝试了一下,但是在执行代码后它没有检索到模型。集合的模型属性为空“[ ]”,但我有模型:Item。 - n0minal
你的Model/Collection网址(localhost/InterprisePOS...)返回什么? - jlb

2

这是由于模型异步加载所致 - 在使用 fetch 加载模型之后,item.get("ItemCode") 才能正常工作。请尝试在 onSuccess 函数中调用它。

另外,请注意直接初始化 Item 是不起作用的。你想要做的是获取集合 Items 中的一个元素,然后在该元素上调用 item.get("ItemCode"),像这样:

function onSuccess() {
   alert('success')
   var item = items.get(13); // get item with id 13
   alert(item.get("ItemCode"));
}

我尝试了你的代码。但是它抛出一个错误,指出(alert(item.get()))中的item未定义。 - n0minal
抱歉,我没有查看AJAX请求的结果。Backbone.js的Collection类希望返回一个数组,而不是嵌套在其中的对象集合项。您能否更改服务器端返回的内容,仅返回“Items”之后的数组? - chiborg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接