Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8961651
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T15:56:35+00:00 2026-06-15T15:56:35+00:00

I am working on my first RequireJS/Backbone app and I’ve hit a wall. There’s

  • 0

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 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T15:56:36+00:00Added an answer on June 15, 2026 at 3:56 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm working on my first large-scale Backbone/RequireJS app, and I have a simple question.
I am working on Ginger Bread source code. First time compilation require 3 to
Working on my first EmberJS app. The entire app requires that a user be
I'm using requirejs for the first time on a project. I'm working in an
I am working on a big Backbone.js application. The code is modular structured using
I am working on application where I use EF code first (v4.4) as ORM
I am working on a Backbone app that requires the input of rows of
Ok, this is my first time to try requireJS, although i dont know what
I am new to wpf and i am working on first application i have
For some weird reason, the codes below are first working, then website is redirecting

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.