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)); を配置すると、テンプレートではなく html に 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 に答える