javascript - How to load views and templates dynamically using backbonejs and requirejs -
i creating form builder application using backbonejs , know how load view dynamically have dropdown can choose type of element should added eg choose input field. have default values go every element in formstemplate , based on field chosen want load different html templates.
define([ 'jquery', 'underscore', 'backbone', 'modal', // pull in collection module 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 = this; this.el.html(buildertemplate); }, // listen events on 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 run code inputtemplate text in html rather template if put $(".formelement").html(_.template(inputtemplate)); works fine. need know how load these dynamically
thanks in advance
you can place require call anywhere if want conditional loading:
edited (added function params 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, did _.bind(...,this) maintain execution scope. know that's not needed here, come in handy.
i in few places in application; when want load modules if , when need them.
Comments
Post a Comment