将doT.js与require.js一起使用

时间:2014-04-05 16:38:32

标签: backbone.js requirejs

我正在使用此处https://github.com/alexanderscott/backbone-login的身份验证示例,而不是使用下划线模板,我想使用doT.js模板。

我已将doT.js源添加到lib目录,我的config.js看起来像这样

if (typeof DEBUG === 'undefined') DEBUG = true;

require.config({

    baseUrl: '/assets',

    paths: {

        //'jquery'            : 'http://code.jquery.com/jquery-1.10.2.js',
        'jquery'              : 'assets/lib/jquery',
        'underscore'            : 'assets/lib/underscore',         // load lodash instead of underscore (faster + bugfixes)

        'backbone'              : 'assets/lib/backbone',
        'bootstrap'             : 'assets/vendor/bootstrap/js/bootstrap',
        'doT'                   : 'assets/lib/doT',
        'text'                  : 'assets/lib/text',
        'parsley'               : 'assets/lib/parsley'

    },

    // non-AMD lib
    shim: {
        //'jquery'                : { exports  : '$' },
        'underscore'            : { exports  : '_' },
        'backbone'              : { deps : ['underscore', 'jquery'], exports : 'Backbone' },
        'bootstrap'             : { deps : ['jquery'], exports : 'Bootstrap' },
        'parsley'               : { deps: ['jquery'] },
        'doT'                   : { exports : 'doT'}

    }

});

require(['main']);           // Initialize the application with the main application file.

我的app.js看起来像这样

define([
    "jquery",
    "underscore",
    "backbone",
    "doT",
    "utils"

],
function($, _, Backbone, doT) {

    var app = {
        root : "/",                     // The root path to run the application through.
        URL : "/",                      // Base application URL
        API : "/api",                   // Base API URL (used by models & collections)

        // Show alert classes and hide after specified timeout
        showAlert: function(title, text, klass) {
            $("#header-alert").removeClass("alert-error alert-warning alert-success alert-info");
            $("#header-alert").addClass(klass);
            $("#header-alert").html('<button class="close" data-dismiss="alert">×</button><strong>' + title + '</strong> ' + text);
            $("#header-alert").show('fast');
            setTimeout(function() {
                $("#header-alert").hide();
            }, 7000 );
        }
    };

    $.ajaxSetup({ cache: false });          // force ajax call on all browsers

    //alert(doT.template("what up {{=it.name}}"),{'name': 'John'});
    // Global event aggregator
    app.eventAggregator = _.extend({}, Backbone.Events);

    return app;

});

和HeaderView.js看起来像这样

define([
    "app",
    "text!templates/header.html",
    "utils",
    "bootstrap"
], function(app, HeaderTpl){

    var HeaderView = Backbone.View.extend({

        template: doT.template(HeaderTpl), //_.template(HeaderTpl),

        initialize: function () {
            _.bindAll(this);

            // Listen for session logged_in state changes and re-render
            app.session.on("change:logged_in", this.onLoginStatusChange);
        },

        events: {
            "click #logout-link" : "onLogoutClick",
            "click #remove-account-link" : "onRemoveAccountClick"
        },

        onLoginStatusChange: function(evt){
            this.render();
            if(app.session.get("logged_in")) app.showAlert("Success!", "Logged in as "+app.session.user.get("username"), "alert-success");
            else app.showAlert("See ya!", "Logged out successfully", "alert-success");
        },

        onLogoutClick: function(evt) {
            evt.preventDefault();
            app.session.logout({});  // No callbacks needed b/c of session event listening
        },

        onRemoveAccountClick: function(evt){
            evt.preventDefault();
            app.session.removeAccount({});
        },


        render: function () {
            if(DEBUG) console.log("RENDER::", app.session.user.toJSON(), app.session.toJSON());
            this.$el.html(this.template({ 
                logged_in: app.session.get("logged_in"),
                user: app.session.user.toJSON() 
            }));
            return this;
        },

    });

    return HeaderView;
});

当我加载页面时,我收到错误

  

未捕获的ReferenceError:未定义doT

我可以调用app.js文件中的doT.template()函数,我可以看到doT.js已加载到我的网络选项卡中,但当我尝试在HeaderView.js中使用它时,我一直收到错误。我是require.js的新手,所以我确定我误解了它是如何工作的。

1 个答案:

答案 0 :(得分:1)

查看doT的来源,我看到它自己调用了define。因此,您不需要shim配置。为调用shim的模块提供define可能会混淆RequireJS。

此外,在这里的情况下,我看到如果doT检测到它是一个AMD环境(RequireJS是),那么在全局空间中将其自身定义为{{ 1}}。因此,您的doT文件必须包含所需模块中的doT。类似的东西:

HeaderView.js
相关问题