define(function(require) {
var $ = require('jquery'),
Backbone = require('backbone'),
People = Backbone.Model.extend({
initialize: function() {
var people_object = new People({name: "How Bizarre", artist: "OMC"});
var people_collections = new PeopleCollection([people_object]);
console.log(people_collections.models);
}
}),
PeopleCollection = Backbone.Collection.extend({
model: People,
});
return {
People: People,
};
});
require(['jquery', 'backbone', 'app/models/persons'], function($,Backbone,persons{
var p = new persons.People();
});
这里我写上面的代码在控制台上显示一些数据,但是当我尝试在控制台上有以下错误消息时我是新来的主干js.can你告诉我哪里错了
<error>
w.pick
a.Model
r
Backbone.Model.extend.initialize
a.Model
r
Backbone.Model.extend.initialize
a.Model
r
Backbone.Model.extend.initialize
a.Model
答案 0 :(得分:0)
首先,您的错误发生在循环依赖(无限循环)中,导致您有一种无限递归。每次初始化像new People()
这样的人时,该模型的initialize
方法都会调用相同的'new Person()'等等....
我猜你正在使用require.js。
所以试试这样:
<强> human.js 强>
define(function(require){
var Backbone = require('backbone');
var Human = Backbone.Model.extend({
defaults: {
name: 'Test',
surname: 'Testovyan',
sex: 1
}
});
return Human;
});
<强> people.js 强>
define(function(require){
var Backbone = require('backbone');
var Human = require('path/to/human');
var People = Backbone.Collection.extend({
initialize: function () {
console.log(this);
},
model: Human,
url: '/path/to/remote/url'
});
return People;
});
<强> controller_or_view.js 强>
define(function(require){
require(['jquery', 'backbone', 'path/to/people'], function () {
var newPeople = [{name: 'John', surname: 'Smith'}, {name: 'Jane', surname: 'Smith'}];
var people = new People(newPeople);
});
});
以下工作fiddle使用相同的代码。
这是创建人物收藏的最佳方式。 创建模型,使用引用模型的模型属性创建集合。然后使用对象数组初始化您的集合,然后它将自动成为模型或在没有模型的情况下初始化您的集合并从远程获取它们。
希望这有帮助。