1

我正在使用backbonejs创建一个表单构建器应用程序,并且想知道如何动态加载视图我有一个下拉列表,我可以在其中选择应该添加什么类型的元素,例如我选择输入字段。我有一些默认值与它们在表单模板中的每个元素一起使用,并且根据选择的字段,我想加载不同的 html 模板。

define([
  'jquery',
  'underscore',
  'backbone',
  'modal',
// Pull in the Collection module from above
  'collections/builder',
  'text!templates/forms/builder.html',
  'text!templates/forms/formsTemplate.html',
  'text!templates/forms/textBox.html',
  'models/builder'

], function ($, _, Backbone, popupModal, attributesCollection, builderTemplate, formsTemplate, inputTemplate, attributesModel) {
    var attributesBuilderView = Backbone.View.extend({
        el: $("#page"),
        initialize: function () {

        },
        render: function () {
            this.loadTemplate();
        },
        loadTemplate: function () {
            var that = this;
            this.el.html(builderTemplate);
        },
        // Listen to events on the current el
        events: {
            "change #attributeType": "loadAttributeTemplate"
        },
        loadAttributeTemplate: function () {
            if ( ($("#attributeType").val()) != '0') {
                $("#attributesArea").append(_.template(formsTemplate, { elementType:              $("#attributeType :selected").text(), _: _ }));
                var template = $("#attributeType").val() + 'Template';
                $(".formElement").html(_.template(template));
            }
        }
    });
    return new attributesBuilderView;
});

在这里,当我运行此代码时,如果我输入 $(".formElement").html(_.template(inputTemplate)); 它工作正常。我只需要知道如何动态加载这些

提前致谢

4

1 回答 1

2

如果您只想进行条件加载,则可以将 require 调用放在任何地方:

已编辑(将函数参数添加到 require 语句中)

loadAttributeTemplate: function () {
    if ( ($("#attributeType").val()) != '0') {
        require(['text!templates/forms/builder.html',
            'text!templates/forms/formsTemplate.html',
            'text!templates/forms/textBox.html'], 
            _.bind(function(builder, formsTemplate, textBox) {
                $("#attributesArea").append(_.template(formsTemplate, { elementType:               $("#attributeType :selected").text(), _: _ }));
                var template = $("#attributeType").val() + 'Template';
                $(".formElement").html(_.template(template));
            },this);
        );
    }
}

注意,我还做了一个 _.bind(...,this) 来维护执行范围。我知道这里不一定需要,但它确实派上用场。

我在我的应用程序的几个地方这样做;尤其是当我只想在需要时才加载模块时。

于 2012-06-12T16:57:46.523 回答