javascriptjquerymodel-view-controllerjquery-eventsjavascriptmvc

How to access the function of different controller? - JavaScript MVC


Assume I have 2 controllers that handle 2 parts of the page - header and page content. Most of the actions happen in pagecontent.js (controller for page content). It has set of functions to load various views. But header has the back button. I track the history, and when the back button is clicked, I want to call the appropriate function on pagecontent.js to load particular view. Here's the example of what I'm trying to do:

pagecontent.js

$.Controller('Controller.Pagecontent', {
  ...
  ".home click": function(){
      this.loadHome();
  },
  loadHome: function(){
      $('#pagecontent').html('//views/home', {});
  }
  ...
})

header.js

$.Controller('Controller.Header', {
  ...
  ".back click": function(){
      if( HISTORY[0] == 'home' )
          // call loadHome() from pagecontent.js
  }
  ...
})

I don't want to copy all those functions to header.js because it will be redundant and some functions have complex logic.

Any ideas?


Solution

  • You can access other controllers functions/events using prototype. Eg. in this situation, it would be like this:

    $.Controller('Controller.Header', {
      ...
      ".back click": function(){
          if( HISTORY[0] == 'home' )
             Controller.Pagecontent.prototype.loadHome();
      }
      ...
    })