I have a Backbone.js web project structured as the following:
├───container
│ container.html
│ ContainerView.js
│
├───home
│ home.html
│ HomeView.js
│
└───search
houses-list-template.html
search.css
search.html
SearchView.js
index.html
The index.html contains all the requirejs definitions such as:
<script type="application/javascript">
requirejs.config({
baseUrl: 'js',
paths: {
text: "requirejs-text-2.0.14",
css: "css",
jquery: "jquery-1.11.3.min",
jquerycolor: "jquery.color",
cookies: "js.cookie",
q: "q",
container:"../views/container/ContainerView",
home: "../views/home/HomeView",
search: "../views/search/SearchView",
And all my subviews looks like this:
define([
"jquery",
"backbone",
'text!../views/container/container.html',
"i18next",
"services",
"q"],
function ($,Backbone, view, i18n,services,Q) {
var ContainerView = Backbone.View.extend({
// many methods
});
return ContainerView;});
Now, the script that launches the application is something like
define(["applicationdef"],function (Application) {
if(window.application ===null || window.application === undefined){
window.application = new Application({container: '#container'});
window.application.start();
}
});
In my application logic I have a ContainerView , defined that attach and detach subviews.
Now, the navigation between views is mediated by the backbone router, that intercepts URL changes and triggers the actions. An action is triggered, the URL changes, and the ContainerView swaps a view and puts in another one. As the content inside the ContainerView is changed, a requirejs-text hook on the ContainerView.html triggers a full reload of my dependencies.
Here is the code inside requirejs-text (release 2.0.14) (check the "callback" invocation"). It triggers a full reload of all the modules and eventually it also causes the Application instances to go out of scope. This breaks all the state of my application.
xhr.onreadystatechange = function (evt) {
var status, err;
//Do not explicitly handle errors, those should be
//visible via console output in the browser.
if (xhr.readyState === 4) {
status = xhr.status || 0;
if (status > 399 && status < 600) {
//An http 4xx or 5xx error. Signal an error.
err = new Error(url + ' HTTP status: ' + status);
err.xhr = xhr;
if (errback) {
errback(err);
}
} else {
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*** the responseText is the content of containerview.html and it triggers a full reload of all the modules.
callback(xhr.responseText);
}
if (masterConfig.onXhrComplete) {
masterConfig.onXhrComplete(xhr, url);
}
}
Am I doing something wrong somewhere ? Thanks a lot.