Where to put onload code in RequireJs and Backbone

2020-07-20 08:04发布

问题:

Doing my first backbone app and I'm using a structure somewhat like this tutorial

I'm wondering where the correct place for me to put my onload code, such as setting up onclick listeners etc would be?

I have:

A simple Bootstrap

require.config({
  paths: {
    jquery: 'libs/jquery/jquery',
    underscore: 'libs/underscore/underscore',
    backbone: 'libs/backbone/backbone'
  }

});

require([

  // Load our app module and pass it to our definition function
  'app',
], function(App){
  // The "app" dependency is passed in as "App"
  App.initialize();
});

The App.js

define(['routers/search'], function(router){
  var initialize = function(){
      this.router = new router();
  } 
  return { initialize: initialize};
});

And then a simple router that calls the relevenent function in the router also defined as a module that calls the relevent function on the router depending on the page.

My feeling is that this function in the router is where I should be putting my onload code. Is that correct?

回答1:

One possibility is to use the RequireJS domReady plugin (it's available for download from their short plugins list): http://requirejs.org/docs/api.html#pageload

Here's the example they give:

require(['domReady'], function (domReady) {
  domReady(function () {
    //This function is called once the DOM is ready.
    //It will be safe to query the DOM and manipulate
    //DOM nodes in this function.
  });
});

So then you can just incorporate it into your normal RequireJS structure, knowing that both the DOM is loaded plus any additional dependencies you might have listed alongside it.