0

我在 require.js 上定义了我的文件配置,如下所示:

require.config({
    shim: {
        'underscore': {
            exports: '_'
        },
        'backbone': {
            deps: ['underscore', 'jquery'],
            exports: 'Backbone'
        },
        'bootstrap': {
            deps: ['jquery']
        }
    },
    paths: {
        jquery: 'libs/jquery-1.10.1',
        underscore: 'libs/underscore',
        backbone: 'libs/backbone',
        bootstrap: 'libs/bootstrap',
        templates: '../templates'
    }
});

require(['app'], function (App) {
    App.initialize();
})

这是我的观点:

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

        var MainView = Backbone.View.extend({

            el: $('.container'),

            events: {
                'click .nav-link.login': 'loginModal'
            },

            loginModal: function() {
                this.$('#login-email, #login-password').val('');
                this.$('#login-modal .alert').addClass('hide');
                this.$('#login-modal').modal();
            }

        });

        return MainView;

});

当我点击 nav-link.login 时,“loginModal”功能被触发,但它不显示我的模态表单,其他指令有效。

但是,如果我打开 javascript 控制台并编写 this.$('#login-modal').modal();,它就可以工作。

我查看 DOM 并按如下方式加载引导程序:

<script type="text/javascript" charset="utf-8" async="" data-requirecontext="_" data-requiremodule="bootstrap" src="js/libs/bootstrap.js"></script>

有人可以帮助我吗?

4

1 回答 1

1

看起来您的 MainView 的 $el 是空的,而且您还没有指定要使用的模板。因此,本质上,当您在 loginModal 中引用“this”时,它会尝试查找与您的 jquery 选择器匹配的第一个 DOM 元素——但它会视图 $el 中查找它,该视图为空。当您从控制台尝试它时,“this”成为全局文档范围,因此您可以找到它。

我的建议是将您的主视图的 html 加载到下划线模板中,并在骨干网的标准渲染函数中渲染它。它可能看起来像这样:

define([
    'jquery',
    'underscore',
    'backbone',
    'bootstrap',
    '!text/path_to_html_templates/MainView.html'
], function ($, _, Backbone, Bootstrap, mainViewTemplate) {

    var MainView = Backbone.View.extend({

        $el: $('.container'),

        template: _.template(mainViewTemplate),

        events: {
            'click .nav-link.login': 'loginModal'
        },

        loginModal: function() {
            this.$('#login-email, #login-password').val('');
            this.$('#login-modal .alert').addClass('hide');
            this.$('#login-modal').modal();
        },

        render: function() {
            this.$el.html(this.template());
        }

    });

    return MainView;

});

我对您的 UI 结构了解不多,无法为您提供更多帮助,但希望至少能给您一个开始。

于 2013-07-11T16:04:48.037 回答