简体   繁体   中英

How to separate code: is my controller doing too much work?

Here is a description of the code below:

  1. router decides which controller method to call
  2. controller gets model(s)
  3. controller instantiates various views with model
  4. controller instantiates layout, puts views into it
  5. controller puts layout into app

Is controller doing too many things? I guess the good way should be

  1. router decides which controller method to call
  2. controller gets model(s)
  3. controller instantiates layout with model
  4. controller puts layout into app. End of controller's work
  5. layout when initialized instantiates views with model

Question : Is the second approach better? If so, how to do [3. and 5. of the good way]?

Code also in jsfiddle

ContactMgr.Router = Marionette.AppRouter.extend({
  appRoutes: {
    'contacts/:id'      : 'detail'
  }
});

ContactMgr.Controller = Marionette.Controller.extend({
    detail: function (id) {
      var promise = App.request('contact:entities', id);
      $.when(promise).done( function (contacts) {
        var _model = contacts.get(id);

        var contactView = new MyContactView({ model: _model });
        var sideView = new MySideView({ model: _model });

        var view = new MyLayout();
        // MyLayout has mainRegion, sideRegion
        view.on('show', function (v) {
          v.getRegion('mainRegion').show(contactView);
          v.getRegion('sideRegion').show(sideView);
        });

        App.getRegion('contentRegion').show(view);
        // App has contentRegion, other regions

      });// when done, end
    }// detail, end
});

This may be the answer.

And

ContactMgr.Controller = Marionette.Controller.extend({
  detail: function (id) {
    ...
    var _model = contacts.get(id);
    ...
    var view = new MyLayout({model: _model});
    App.getRegion('contentRegion').show(view);
  }
});

MyLayout = Marionette.Layout.extend({
    ...
    regions: {
      mainRegion: '#...',
      sideRegion: '#...'
    },
    contactView: null,
    sideView: null,
    onShow: function () {
      this.getRegion('mainRegion').show(this.contactView);
      this.getRegion('sideRegion').show(this.sideView);
    },
    initialize: function (opt) {
      var _model = opt.model;
      this.contactView = new Marionette.ItemView({ model: _model });
      this.sideView    = new Marionette.ItemView({ model: _model });
    }

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM