Continuing my quest to learn more about Backbone.js I have arrived to a situation where I would want to instantiate a Backbone application programmatically. This occurs in a situation where the entire site/page is not a Backbone application, but instead a modal is opened, then populated (base structure for Backbone app), and then I would like to trigger the Backbone application (whose JavaScript was also loaded when the modal was opened). I would prefer to instantiate the Backbone app 'manually' if possible, i.e. so that it would not auto-execute when its script is loaded.
The typical Backbone format I have been using is like this:
var myApp = (function($) {
var myModel = Backbone.Model.extend({
...
});
var modelInstance = new myModel({
...
});
var myView = Backbone.View.extend({
...
});
var viewInstance = new myView({
...
});
}
But the above is automatically executed when the script file is loaded, then the instantiated view(s) attempt to bind/render to their associ开发者_运维问答ated DOM elements, etc. Is there a way to defer the execution of the anonymous function so that I could load the script when the modal is being prepared but then trigger the Backbone app on command at a [slightly] later point?
Many thanks for any insights on this.
You should put your app's components into an object with an init
method, which you can then call when your modal dialog opens. Here's an example structure:
window.App = {
Models: {},
Views: {},
Routers: {},
init: function () {
var app = new window.App.Routers.main;
Backbone.History.start();
return app;
}
};
window.App.Models.Foo = Backbone.Model.extend({
// ...
});
window.App.Views.FooView = Backbone.View.extend({
// ...
});
window.App.Routers.main = Backbone.Router.extend({
// ...
});
window.modalDialog.onOpen = function () {
window.app = window.App.init();
};
The above assumes you have a global variable called modalDialog
representing your modal window, which calls its onOpen
callback when the window is shown.
精彩评论