我正在尝试在我的项目中实现RequireJS并遇到一些问题。我收到的错误是我的物品型号。在模型中,我正在尝试将属性设置为新集合。在该行中,我收到以下错误:“未捕获的TypeError:undefined不是函数。”
我的路由器看起来像这样:
define(['backbone', 'collections/items', 'views/itemsView'], function (Backbone, Items, ItemsView) {
var Workspace = Backbone.Router.extend({
routes: {
'*path': 'nearby'
},
nearby: function() {
var items = new Items();
items.fetch();
var itemsView = new ItemsView({
collection: items
});
});
return Workspace;
});
收集:
define(['backbone', 'models/item', 'tastypie'], function(Backbone, Item) {
var Items = Backbone.Collection.extend({
url: function() {
var url;
url = '/api/v1/nearby/?lat=' + lat1 + '&lng=' + lon1;
return url;
},
model: Item,
});
return Items;
});
型号:
define(['backbone', 'collections/locations'], function (Backbone, Locations) {
var Item = Backbone.Model.extend({
urlRoot: '/api/v1/item',
url: function () {
// stuff here
},
set: function (attrs) {
// Making a new Locations collection ordered by distance
if (attrs.items && attrs.items.length > 0) {
// Sets the collection as an attrubute
// The following line is where I get the error
attrs.locations = new Locations(attrs.items);
Backbone.Model.prototype.set.apply(this, [attrs]);
// Sets the closest attribute
attrs.closest = this.get('locations').getClosestItem().get('distance');
Backbone.Model.prototype.set.apply(this, [attrs]);
attrs.numItems = this.get('items').length;
Backbone.Model.prototype.set.apply(this, [attrs]);
}
return Backbone.Model.prototype.set.apply(this, [attrs]);
},
});
return Item;
});
任何人都知道我为什么会收到错误?我确保在我的模型中定义了Location集合。
编辑:添加locations.js文件:
define(['backbone', 'models/location'], function (Backbone, LocationModel) {
var Locations = Backbone.Collection.extend({
model: LocationModel,
comparator: function(item) {
return item.get('distance') + ' ' + item.get('name');
},
getClosestItem: function() {
return this.at(0);
}
});
return Locations;
});
感谢您的帮助。