我正在使用 backbonejs 创建一个表单生成器应用程序,想知道如何动态加载 View 我有一个下拉菜单,我可以在其中选择应该添加什么类型的元素,例如我选择输入字段。我有一些默认值与它们在 formtemplate 中的每个元素一起使用,并且根据选择的字段我想加载不同的 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 文本,而不是模板。它工作正常。我只需要知道如何动态加载这些
提前致谢
最佳答案
如果你只想进行条件加载,你可以在任何地方调用 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) 来维护执行范围。我知道这里不一定需要,但它确实派上用场。
我在应用程序的几个地方这样做;特别是当我只想在需要时才加载模块。
关于javascript - 如何使用 backbonejs 和 requirejs 动态加载 View 和模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11000999/