对象不是函数'尝试用需求实例化木偶应用程序时出现错误

'Object is not a function' error when trying to instantiate Marionette Application with requirejs

本文关键字:实例化 应用程序 错误 需求 函数 对象      更新时间:2023-09-26

这是我第一次尝试使用木偶。我试图实例化一个木偶应用程序作为一个需求模块。我一直在木偶。js wiki上使用木偶与Require js文章:-

https://github.com/marionettejs/backbone.marionette/wiki/Using-marionette-with-requirejs

我认为我有我所有的shims,依赖关系和文件的顺序,因为我能够实例化视图,模型等在同一个地方没有错误,但我无法找出我的应用程序的问题。任何帮助或指导将非常感激!

这是我的index.html:-

<!DOCTYPE html>
<html>
<head>
    <title>Marionette Structure and Require AMD Proto</title>
    <link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<div id="nav">
</div>
<div id="mainContent">
</div>
<script language="javascript">
    // convenience function, because console.log throws errors and crashes IE
    // this way you don't need to all logs to test in IE
    function trace(msg){
        try{
            console.log(msg);
        }catch(e){
            // suppressed error
        }
    }
</script>
<script src="js/lib/require.js" data-main="app.js"></script>
</body>
</html>

我的app.js:-

require.config({
    paths : {
        backbone : 'js/lib/backbone',
        underscore : 'js/lib/underscore',
        jquery : 'js/lib/jquery',
        marionette : 'js/lib/backbone.marionette'
    },
    shim : {
        jquery : {
            exports : 'jQuery'
        },
        underscore : {
            exports : '_'
        },
        backbone : {
            deps : ['jquery', 'underscore'],
            exports : 'Backbone'
        },
        marionette : {
            deps : ['jquery', 'underscore', 'backbone'],
            exports : 'Marionette'
        }
    }
})
require(
    ["jquery",
        "underscore",
        "backbone",
        "marionette",
        "js/shell/shellapp"
    ],
    function($, _, Backbone, Marionette, ShellApp) {
        $(function() {
           new ShellApp();
            trace("ShellApp: "+ShellApp);
        });
    }
);

最后这里是我的shellapp.js:-

define( ["marionette"], function (Marionette) {
    // set up the app instance
    var ShellApp = new Marionette.Application();
    // configuration, setting up regions, etc ...
    ShellApp.addRegions({
        nav: '#nav',
        main: '#mainContent'
    });
    ShellApp.on('initialize:after', function(){
        trace("initialize:after");
    });
    // export the app from this module
    return ShellApp;
});

把所有这些放在一起,我得到"Uncaught TypeError: object is not a function "在app.js第42行

非常感谢所有走到这一步的人!

山姆

我的回答太长了,不能评论!

导出的是一个构造对象,而不是构造函数本身:

var ShellApp = new Marionette.Application()
...
return ShellApp;

,这正是要导入的内容,因此您不需要创建另一个new

首先,我将ShellApp重命名为shellApp以表示实例,而不是构造函数(这是一种常见的命名约定)。我认为在教程中,他们打破了这个惯例,这是相当误导的:

MyApp = new Backbone.Marionette.Application();

(假设我没写错)。

我现在假设你只是传递这个Marionette.Application的单个实例,在你的应用程序的生命周期。

在本教程中,它显示导出更新的 Marionette.Application(与您所做的相同),但不显示在导入时实际使用它。在导入对象之后,您可以访问它的属性,例如:

shellApp.addInitializer(function(options){
    // stuff
});
这里多