0

I am new to Javascript and Backbone and maybe it is a stupid question. I have this Collection

define(['backbone', 'models/profile'], function(Backbone, Profile) {

  // Collection definition
  var Profiles = Backbone.Collection.extend({
    url: '/profile',
    model: Profile,
    //localStorage: new Backbone.LocalStorage('Profiles'),

    initialize: function() {    
        this.fetch();

        if (this.isEmpty() || !this.where({is_guest: true}))
            this.create({name: 'Guest', is_guest: true, has_pin: false});
     }
  });

  return Profiles;

});

I want to add items to this collection from the console in the chrome, I tried collection.create({name: 'Guest', is_guest: true, has_pin: false}); and Profiles.create({name: 'Guest', is_guest: true, has_pin: false}); but it says that it is undefined. Can someone explain me why, or what I am doing wrong?

4

3 回答 3

0

不要忘记这Profiles仅在您上面的文件范围内,您无法从外部访问它。由于您使用的是Profiles.create({...我假设您尚未初始化集合。

只是一个提示:

文件 1:您的收藏

文件 2:

define(['collections/my_collection_from_above'], function(MyCollectionFromAbove) {
    var myCollection = new MyCollectionFromAbove();
    myCollection.create({....});
}); 

或另一种情况:

var MyCollectionFromAbove = require('collections/my_collection_from_above');
var myCollection = new MyCollectionFromAbove();
myCollection.create({....});

当然......我只是在猜测你想要做什么。

于 2013-11-05T20:14:29.343 回答
0

听起来对我来说也是一个范围问题,因为代码看起来不错(好吧,你在构造函数中异步调用 fetch(),所以你 isEmpty() 可能会失败......但这是一个不同的问题)。您正在使用 AMD/Require.js,因此请提供作为依赖项加载此集合的模块的代码。

于 2013-11-05T12:29:06.197 回答
0

在浏览器中使用 this 检查上下文并检查集合对象是否在范围内。简单地在控制台中输入 collection 是行不通的。或者提供更多细节。

于 2013-11-05T07:39:23.430 回答