The function is assuming that the file has been already require'd. This will instantiate a View for the key, if it has not already been instantiated and return the result or the cached View.
"use strict";
var viewCache = {};
/**
* The function is assuming that the file has been already require'd.
* This will instantiate a View for the key, if it has not already been
* instantiated and return the result or the cached View.
*
* @param {String} key the key for the View required; my
* implementation uses the filename
* @param {Object} ViewClass object representing the View "Class"
* @param {Object} options associative array of options; the normal
* parameter expected by the constructor
* @param {Array} otherParameters additional parameters your constructor
* or initialize method might expect
* @return {Object} instantiated or cached View
*/
function getView(key, ViewClass, options, otherParameters) {
var view, parameters = [];
// If the View is used for the first time, we instantiate it.
if (_.isUndefined(viewCache[key])) {
// The problem is that we receive otherParameters as an array,
// but we can't pass it directly to the constructor. We could
// use apply, but then we don't have an Object to apply the
// constructor on. We could get in weird errors regarding the
// scope in which the constructor is run.
//
// To avoid this, we instantiate the View using the new keyword,
// then we apply the constructor using the additional parameters,
// if that array is not empty.
view = new ViewClass(options);
if (!_.isEmpty(otherParameters)) {
ViewClass.apply(view, otherParameters);
}
viewCache[key] = view;
// If the View exists in the cache, re-initialize it.
} else {
// We have to build the parameters array to be passed to the
// constructor.
if (!_.isUndefined(options)) {
parameters.push(options);
}
if (!_.isUndefined(otherParameters)) {
parameters = parameters.concat(otherParameters);
}
view = viewCache[key];
view.stopListening();
view.undelegateEvents();
ViewClass.apply(view, parameters);
}
return viewCache[key];
}