2

这是我第一次尝试使用 Marionette。我正在尝试将 Marionette 应用程序实例化为 requirejs 模块。我一直在关注 Marionette.js wiki 上的 Using Marionette with Require js 文章:-

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

我想我有我所有的垫片、依赖项和文件,因为我能够在同一个地方实例化视图、模型等而不会出错,但我无法弄清楚我的应用程序的问题。任何帮助或指导将不胜感激!

这是我的 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;
});

把它们放在一起,我在 app.js 第 42 行得到“Uncaught TypeError: object is not a function”

非常感谢能走到这一步的任何人!

山姆

4

1 回答 1

3

我的回答太长了,无法发表评论!

您正在导出构造的对象,而不是构造函数本身:

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

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

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

MyApp = new Backbone.Marionette.Application();

(假设我在这里是正确的)。

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

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

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

更多在这里

于 2013-04-11T13:52:06.023 回答