Backbone vanilla模型返回undefined为'set'

时间:2014-05-20 05:08:52

标签: javascript jquery backbone.js

app.js

define([
  'jquery',
  'underscore',
  'backbone',
  'background',
  'views/popup',
  'views/playlist',
  'models/popup',
], function($, _, Backbone, Background, PopupView, PlaylistView, PopupModel) {
  var init = function() {
    console.log("app: init")
    var bg = chrome.extension.getBackgroundPage();
    var popupModel = PopupModel();
  };

  return {
    init: init
  };

});

模型/ popup.js

define([
  'jquery',
  'backbone',
], function($, Backbone){
  console.log("inside popupModel") // this is called
  var PopupModel = Backbone.Model.extend({
    initialize: function() {
      alert("hey") // this is NOT called. Error occurs before this.
    }
  });
  // Return the model for the module
  return PopupModel;
});

问题:当我尝试创建新的PopupModel时,我不断获得undefined is not a function,这会跟踪Backbone中的以下源代码。

var Model = Backbone.Model = function(attributes, options) {
    var attrs = attributes || {};
    options || (options = {});
    this.cid = _.uniqueId('c');
    this.attributes = {};
    if (options.collection) this.collection = options.collection;
    if (options.parse) attrs = this.parse(attrs, options) || {};
    attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
    this.set(attrs, options); // ERROR HERE; this.set is undefined for an unknown reason.
    //console.log(this) outputs a WINDOW object. I don't know why.

我很困惑为什么我在上面的设置中看到这样的错误。有谁可以帮助我?

1 个答案:

答案 0 :(得分:2)

要创建模型的实例,您应该使用new关键字。

var popupModel = new PopupModel();

作为建议,不要在模块中定义用于存储模型的变量,只需要return它:return Backbone.Model.extend({});