获取backbone.js中模型的属性

jon*_*aag 7 javascript ajax rest backbone.js

我有这个模型

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

var onSuccess = function(){ alert("success"); };
Run Code Online (Sandbox Code Playgroud)

还有一个系列

var Items = Backbone.Collection.extend({
    model: Item
});
Run Code Online (Sandbox Code Playgroud)

其余的代码在这里:

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

我想要的是简单地获取模型的属性.现在我在萤火虫上有这个.此外,当我在浏览器上运行它时,我获得警报成功,并且下一个警报未定义. 在此输入图像描述

这是输出:

{"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}]}
Run Code Online (Sandbox Code Playgroud)

注意

这只是它返回的项目之一.我刚刚发布了项目,所以它不会那么久.

jlb*_*jlb 11

您正在调用get您的集合(请参阅http://documentcloud.github.com/backbone/#Collection-get)

看起来你真正想要的是迭代集合,并调用每个项目的get

items.each(function(item) {
  item.get('ItemCode');
});
Run Code Online (Sandbox Code Playgroud)

如果没有,请详细说明!

此外,如果模型URL响应模型列表,则应该在集合中定义url属性而不是模型.

var Items = Backbone.Collection.extend({
    model: Item,
    url: 'http://localhost/InterprisePOS/Product/loaditembycategory/Event Materials'
});
Run Code Online (Sandbox Code Playgroud)

并且您的响应应该是一个数组,Items作为数组元素[<item1>, <item2>, ...],而不是JSON对象{'Items': [<item1>, <item2>, ...] }.如果您不想修改响应,则必须parse在集合上实现该功能(http://documentcloud.github.com/backbone/#Collection-parse).

此外,作为@chiborg提到,您呼叫的get右后fetch(这将异步完成),所以不能保证您的数据将可用.

这里适当的解决方案是绑定集合上的"刷新"侦听器.

items.on('refresh', function() {
  // now you have access to the updated collection
}, items);
Run Code Online (Sandbox Code Playgroud)