尝试使用我的收藏时,获取“未定义不是函数”

时间:2013-04-12 21:26:56

标签: javascript backbone.js requirejs

我正在使用RequireJS来处理所有依赖项。

所以这是我的观点:

define([
    'jquery',
    'underscore',
    'backbone',
    'bootstrap',
    'collections/InstitutionsCollection'
], function($, _, Backbone, InstitutionsCollection){

    var InstitutionsView = Backbone.View.extend({
        render: function() {
            var institutions = new InstitutionsCollection();

            institutions.fetch({
                success: function() {
                    console.log("success!");
                }
            });
        }
    });

    return InstitutionsView;
});

此行引发错误: var institutions = new InstitutionsCollection();

这是我的收藏:

define([
    'jquery',
    'underscore',
    'backbone',
    'models/InstitutionModel'
], function($, _, Backbone, InstitutionModel){

    var InstitutionsCollection = Backbone.Collection.extend({
        model: InstitutionModel,
        url: '/institutions/'
    });

    return InstitutionsCollection;
});

如果你需要它,这是我的模型:

define([
    'jquery',
    'underscore',
    'backbone'
], function($, _, Backbone){

    var InstitutionModel = Backbone.Model.extend({

    });

    return InstitutionModel;
});

我已经盯着它看了一会儿,我无法弄清楚为什么它会抛出那个错误。非常感谢任何帮助。

3 个答案:

答案 0 :(得分:4)

正如其他人所建议的那样,您的define回调参数的顺序与错误匹配。我想指出糖语法有助于缓解这个常见错误:

define(function(require) {
    var $ = require('jquery');
    var _ = require('underscore');
    var Backbone = require('backbone');
    var InstitutionsCollection = require('collections/InstitutionsCollection');
    require('bootstrap');

    var InstitutionsView = Backbone.View.extend({
        // Code
    });

    return InstitutionsView
});

详细了解in the documentation

答案 1 :(得分:3)

定义view时,您要导入引导程序并将其映射到require回调中的InstitutionsCollection参数。尝试更新您的代码,如下所示:

define([
    'jquery',
    'underscore',
    'backbone',
    'collections/InstitutionsCollection',
    'bootstrap'
], function($, _, Backbone, InstitutionsCollection){

    var InstitutionsView = Backbone.View.extend({
        render: function() {
            var institutions = new InstitutionsCollection();

            institutions.fetch({
                success: function() {
                    console.log("success!");
                }
            });
        }
    });

    return InstitutionsView;
});

保持映射同步真的很痛苦,扫描代码时很容易忽略!

答案 2 :(得分:2)

您正在将bootstrap映射到InstitutionsCollection。将其更改为:

define([
  'jquery', 'underscore', 'backbone', 'collections/InstitutionsCollection',           
  'bootstrap'
], function($, _, Backbone, InstitutionsCollection){});