2
votes

I am working on my first RequireJS/Backbone app and I've hit a wall. There's a lot of code smell here, and I know I'm just missing on the pattern.

I have a route that shows all promotions, and one that shows a specific promotion (by Id):

showPromotions: function () {
    var promotionsView = new PromotionsView();
},
editPromotion: function (promotionId) {
    vent.trigger('promotion:show', promotionId);
}

In my promotions view initializer, I new up my PromotionsCollection & fetch. I also subscribe to the reset event on the collection. This calls addAll which ultimately builds a ul of all Promotions & appends it to a container div in the DOM.

define([
  'jquery',
  'underscore',
  'backbone',
  'app/vent',
  'models/promotion/PromotionModel',
  'views/promotions/Promotion',
  'collections/promotions/PromotionsCollection',
  'text!templates/promotions/promotionsListTemplate.html',
  'views/promotions/Edit'
], function ($, _, Backbone, vent, PromotionModel, PromotionView, PromotionsCollection, promotionsListTemplate, PromotionEditView) {
    var Promotions = Backbone.View.extend({
        //el: ".main",
        tagName: 'ul',
        initialize: function () {
            this.collection = new PromotionsCollection();
            this.collection.on('reset', this.addAll, this);
            this.collection.fetch();
        },

        render: function () {
            $("#page").html(promotionsListTemplate);
            return this;
        },
        addAll: function () {
            //$("#page").html(promotionsListTemplate);
            this.$el.empty().append('<li class="hide hero-unit NoCampaignsFound"><p>No campaigns found</p></li>');
            this.collection.each(this.addOne, this);
            this.render();
            $("div.promotionsList").append(this.$el);
        },

        addOne: function (promotion) {
            var promotionView = new PromotionView({ model: promotion });
            this.$el.append(promotionView.render().el);
        }    
    });
    return Promotions;
});

Each promotion in the list has an edit button with a href of #promotion/edit/{id}. If I navigate first to the list page, and click edit, it works just fine. However, I cannot navigate straight to the edit page. I understand this is because I'm populating my collection in the initialize method on my View. I could have a "if collection.length == 0, fetch" type of call, but I prefer a design that doesn't have to perform this kind of check. My questions:

  1. How do I make sure my collection is populated regardless of which route I took?
  2. I'm calling render inside of my addAll method to pull in my template. I could certainly move that code in to addAll, but overall this code smells too. Should I have a "parent view" that's responsible for rendering the template itself, and instantiates my list/edit views as needed?

Thanks!

1

1 Answers

2
votes

Here's one take. Just remember that there is more than one way to do this. In fact, this may not be the best one, but I do this myself, so maybe someone else can help us both!

First off though, you have a lot of imports in this js file. It's much easier to manage over time as you add/remove things if you import them like this:

define(function( require ){
  // requirejs - too many includes to pass in the array
  var $ = require('jquery'),
      _ = require('underscore'),
      Backbone = require('backbone'),
      Ns = require('namespace'),
      Auth = require('views/auth/Auth'),
      SideNav = require('views/sidenav/SideNav'),
      CustomerModel = require('models/customer/customer');
      // blah blah blah...});

That's just a style suggestion though, your call. As for the collection business, something like this:

  Forms.CustomerEdit = Backbone.View.extend({

    template: _.template( CustomerEditTemplate ),

    initialize: function( config ){
      var view = this;
      view.model.on('change',view.render,view);
    },

    deferredRender: function ( ) {
      var view = this;
      // needsRefresh decides if this model needs to be fetched.
      // implement on the model itself when you extend from the backbone
      // base model.
      if ( view.model.needsRefresh() ) {
        view.model.fetch();
      } else {
        view.render();        
      }
    },

    render:function () {
      var view = this;
      view.$el.html( view.template({rows:view.model.toJSON()}) );
      return this;
    }

  });


   CustomerEdit = Backbone.View.extend({

    tagName: "div",

    attributes: {"id":"customerEdit",
                 "data-role":"page"},

    template: _.template( CustomerEditTemplate, {} ),


    initialize: function( config ){
      var view = this;
      // config._id is passed in from the router, as you have done, aka promotionId
      view._id = config._id;

      // build basic dom structure
      view.$el.append( view.template );

      view._id = config._id;
      // Customer.Foo.Bar would be an initialized collection that this view has
      // access to.  In this case, it might be a global or even a "private" 
      // object that is available in a closure 
      view.model = ( Customer.Foo.Bar ) ? Customer.Foo.Bar.get(view._id) : new CustomerModel({_id:view._id});

      view.subViews = {sidenav:new Views.SideNav({parent:view}),
                       auth:new Views.Auth(),
                       editCustomer: new Forms.CustomerEdit({parent:view,
                                      el:view.$('#editCustomer'),
                                      model:view.model})
                                    };

    },

    render:function () {
      var view = this;
      // render stuff as usual
      view.$('div[data-role="sidetray"]').html( view.subViews.sidenav.render().el );
      view.$('#security').html( view.subViews.auth.render().el );
      // magic here. this subview will return quickly or fetch and return later
      // either way, since you passed it an 'el' during init, it will update the dom
      // independent of this (parent) view render call.
      view.subViews.editCustomer.deferredRender();

      return this;
    }

Again, this is just one way and might be terribly wrong, but it's how I do it and it seems to work great. I usually put a "loading" message in the dom where the subview eventually renders with replacement html.