Javascript 获取backbone.js中模型的属性

Javascript 获取backbone.js中模型的属性,javascript,ajax,rest,backbone.js,Javascript,Ajax,Rest,Backbone.js,我有这个型号 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 = 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"));
我想要的是简单地获得模型的属性。现在我有这个关于萤火虫的。另外,当我在浏览器上运行它时,我会收到警报success,下一个警报是undefined

这是输出:

{"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}]}

这只是它返回的项目之一。我刚刚发布了一个项目,这样它就不会那么长。

这是由于模型异步加载-
项目。get(“ItemCode”)
只有在模型加载了
fetch
之后才能工作。尝试在onSuccess函数中调用它

此外,请注意,直接初始化
也没有帮助。您试图做的是在集合
Items
中获取一个元素,然后对该元素调用
item.get(“ItemCode”)
,如下所示:

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

您正在对您的收藏呼叫
get
(请参阅)

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

items.each(function(item) {
  item.get('ItemCode');
});
如果没有,请详细说明

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

var Items = Backbone.Collection.extend({
    model: Item,
    url: 'http://localhost/InterprisePOS/Product/loaditembycategory/Event Materials'
});
您的响应应该是一个数组,其中项作为数组元素
[,…]
,而不是带有
{'Items':[,…]}
的JSON对象。如果不想修改响应,则必须在集合()上实现
parse
函数

此外,正如@chiborg所提到的,您在
fetch
之后立即调用
get
(将异步完成),因此无法保证您的数据可用

这里的正确解决方案是在集合上绑定一个“刷新”侦听器

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

我试过你的密码。但是我抛出了一个错误,指出来自(alert(item.get())的项未定义。很抱歉,我没有查看AJAX请求的结果。Backbone.js的Collection类要求返回一个数组,而不是嵌套集合项的对象。您能否更改服务器端返回的内容,返回jsut“Items”后面的数组?对于模型部分,很抱歉。我只是在做实验,因为我注意到模型项没有得到它的空属性。还有关于解析的事情。我试过了,但是在我执行代码之后,它没有检索到模型。集合的model属性为空“[]”,但我有model:item您的模型/集合url(localhost/InterprisePOS…)返回什么?