javascript - 主干普通模型返回未定义的 'set'

标签 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
  };

});

models/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.

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

最佳答案

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

var popupModel = new PopupModel();

建议不要在模块中定义不必要的变量来存储模型,只需返回它:return Backbone.Model.extend({}) ;

关于javascript - 主干普通模型返回未定义的 'set',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23751428/

相关文章:

javascript - 主干监听集合上的更改事件

javascript - 如何从 server.js 向 Controller 发送请求?

javascript - 如何使用 javascript 在有序列表中显示文本

javascript - 使用 clamp.js 在 React 中进行线夹导致 IE11 中的对象错误

javascript - 将 JavaScript 插入 JavaScript 警报

javascript - 使用 Backbone.js 填充在 save() 上发送的 JSON 对象

javascript - 使用 Bootstrap PHP 表单向导插入到 sql

html - 如何处理深层嵌套的导航菜单?

java - Spring MVC + JQuery + Ajax 问题

backbone.js - Jinja2、Backbone.js 和渐进增强