Reputation: 1912
I am creating a form builder application using backbonejs and would like to know how load view dynamically I have a dropdown where i can choose what type of element should be added eg i choose input field. i have some default values that go with every element they are in formstemplate and based on what field is chosen i want to load different html templates.
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;
});
here when i run this code i get inputTemplate text in the html rather than template if i put $(".formElement").html(_.template(inputTemplate)); it works fine. I just need to know how to load these dynamically
Thanks in advance
Upvotes: 1
Views: 2199
Reputation: 1145
You can place the require call anywhere if you only want to do conditional loading:
edited (added the function params to the require statement)
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);
);
}
}
Note, I also did a _.bind(...,this) to maintain the execution scope. I know that's not necessarily needed here, but it does come in handy.
I do this in a few places in my application; especially when I want to load modules only if and when I need them.
Upvotes: 2