0

我想使用 Require.js 文本为 Backbone 视图加载外部 HTML 模板!插件并自定义模板路径(从查看“模板”属性获取模板路径)。问题是 - 模板异步加载并且在渲染时我仍然没有它。这是我的代码:

自定义视图

define([
    'views/abstract/base-view',
], function (BaseView) {

    var AppView = BaseView.extend({

        el: '#app-view',

        template: 'app-view',

        initialize: function () {

            this.on('template:loaded', this.render, this);

            BaseView.prototype.initialize.apply(this, arguments);

        },

        render: function () {

            this.$el.empty();

            var html = this.template();

            this.$el.html(html);
        }
    });

    return AppView;

});

和抽象视图继承

define([], function () {

    var AbstractView = Backbone.View.extend({

        initialize: function(){
            this.setTemplate();
        },

        setTemplate: function(){
            var that = this;
            require(['3p/text!templates/' + this.template + '.tpl'], function(tpl) {
                that.template = _.template(tpl);
                that.trigger('template:loaded');
            });
        }
    });

    return AbstractView;

});

它有效,但我不喜欢听“模板:加载”事件进行渲染。有什么建议么?谢谢!

4

1 回答 1

0

我有同样的问题。为了避免异步行为,除了在某些文件中添加将是动态的需求并在之前加载所有这些需求之外,没有其他方法。

我做了一些类似于注射的东西。我加载了所有动态模板,并将模板的路径放入共享字典中。然后我使用 _.template(require(inject["templateNAME"])) 并且我现在得到了模板。

这个想法类似于下一个:

define(["require"], function (require) {
    require(["text!path/of/the/template",
             ...  ]);

    window.inject = {};
    inject.templateNAME = "text!path/of/the/template";

然后你会使用这样的东西:

var tpl = require(inject[this.templateName]);
this.template = _.template(tpl);
于 2013-10-25T13:03:28.163 回答