Backbone es una biblioteca realmente elegante, liviana y flexible, y debido a su flexibilidad, te deja un gran espacio para que funcione como un “marco”. Aquí hay un ejemplo de cómo escribir una subvista de Backbone muck-up que puede permitirle colocar su subvista en el html en lugar de combinarlas en JavaScript.
Dependencias
Para implementar la subvista en el muck-up, necesitamos las siguientes bibliotecas para trabajar con Backbone juntas:
Bigote daliniano
Underscorejs
Requirejs
Jquery
Uso
Veamos primero cómo funciona. Ponga el fragmento de abajo en su html y deje el resto del trabajo a The Handlebars
{{render model id="myRenderer" class="myClass" renderer="path.of.renderer" otherAttributes}}
o
{{render renderer="path/of/renderer" otherAttributes}}
Implementar
// A subview holder of the current stage. Can be used to
// retrieve the views, or tear down when leave the stage.
var stage = [];
(function() {
Handlebars.registerHelper('render', function(context, options) {
var attributeHash = (options && options.hash) || context.hash,
tag = attributeHash.tag || "div",
viewModel = options ? context : null,
token = _.uniqueId();
if (attributeHash.renderer)
// Make sure the render action is always asynchronously.
setTimeout(function() {
render(token, tag, viewModel, attributeHash);
}, 0);
else
throw new Error(
"Backbone sub view renderer requires a 'renderer' attribute.");
// Return the html place holder.
return new Handlebars.SafeString(
[ "<", tag," renderer-id='", token, "'></", tag,">" ].join(""));
});
function render(token, tag, model, hash) {
require([ hash.renderer ], function(SubView) {
var $placeHolder = $([ tag, "[renderer-id=", token, "]" ].join("")),
subView = null;
if (SubView.prototype instanceof Backbone.View) {
subView = new Renderer({
token: token,
model: model,
attributes: _.omit(hash, "tag")
});
stage.push({
token: token,
view: subView
});
$placeHolder.replaceWith(renderer.$el);
} else {
throw new Error(
"The subview renderer must inherit from Backbone.View.");
}
});
}
})();