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 9265311
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T14:02:25+00:00 2026-06-18T14:02:25+00:00

I’m building a simple Backbone application with a search form and some results. I’d

  • 0

I’m building a simple Backbone application with a search form and some results. I’d like to:

  • allow the user to change the value of an ‘order by’ select field, and update the URL and results appropriately
  • ensure that when the user arrives via a preset URL, the correct results are shown, and the selected form elements match the URL and results.

I think I’ve figured out the right control flow to use, but I’d really like to have someone sanity-check it. Basically, I’m letting my Views update the URLs directly, and then the Router does the work of updating the Model. Other Views then listen to the Model.

It seems to work OK, but I have to construct the URL by hand in the View, and parse it again in the Router, which feels repetitive. So it would just be great to know if this is the right way to do things in Backbone, or if I can do things better.

Here’s the pseudocode:

 User changes value of select to "price-asc"    
           |                                        
           |                                        
           v                                        
 Form view hears change event, and              
 updates the URL to #order-by-price-asc            
           |                                       
           |                                       
           v                                       
 Router looks at new route,        <----- User loads page, with 
  sets model value                       #order-by-price-asc route
           |
           |
           v   
  Results view hears change 
  to model value, loads in 
  new results via Ajax

Here is the code:

HTML:

<select id="order">
    <option value=''></option>
    <option value='price-asc'>price (low to high)</option>
    <option value='price-desc'>price (high to low)</option>
</select>
<div id="results"></div>

JS:

var SearchModel = Backbone.Model.extend({
    initialize: function() {
        this.bind("change:query", function() {
        this.performSearch();
        });
    },
    performSearch: function() {
        // Will eventually do Ajax search here, 
        // but for the moment, just bind to query. 
        this.set("results", this.get("query"));
    },
});

var SearchFormView = Backbone.View.extend({
    el: $('#order'),
    events: {
        "change": "updateURL"
    },
    initialize: function() {
        this.model.on("change:results", this.updateFormClasses, this);
    },
    updateFormClasses: function(model, query) {
        this.$el.val(query);
    },
    updateURL: function(e) {
        var url = '';
        ($('#order').val() !== '') ? url += "/by-" + $('#order').val() : null;
        SearchApp.navigate(url, {trigger: true});
    }
});

var SearchResultsView = Backbone.View.extend({
    el: "#results",
    initialize: function() {
        this.model.on("change:results", this.displayResults, this);
    },
    displayResults: function(model, query) {
        this.$el.text(query)
    }
});

var AppRouter = Backbone.Router.extend({
    routes: {
    "*str": "index",
    },
    initialize: function() {
        this.searchModel = new SearchModel();
        this.searchFormView = new SearchFormView({
            model: this.searchModel
        });
        this.searchResultsView = new SearchResultsView({
            model: this.searchModel
        });
    },
    index: function(str) {
        var ordering = str.match(/by-.*/gi);
        if (ordering !== null) {
            this.searchModel.set({"query": ordering[0].replace('by-','')});
        }
    }
});
var SearchApp = new AppRouter();
Backbone.history.start({});
  • 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-18T14:02:26+00:00Added an answer on June 18, 2026 at 2:02 pm

    There are few optimizations you can do:

    1. Use an optional route parameter instead of parsing the url manually:

      var AppRouter = Backbone.Router.extend({
          routes: {
            "*str(/by-:sort)": "index",
          },
          index: function(str, sort) {
            if(sort) {
              //...
            }
          }
      });
      
    2. Consider allowing view to handle the model change, instead of going via the router. In order to avoid code duplication, encapsulate this logic in a model method.

      var SearchModel = Backbone.Model.extend({
        sort: function(field) {
          this.set({query:field});
        }
      });
      
      var SearchFormView = Backbone.View.extend({
        el:"#order",
        events: {
          "change": "updateSort"
        },
        updateSort: function(e) {
          var sortOrder = this.$el.val();
      
          //update model
          this.model.sort(sortOrder);
      
          //navigate without trigger:true, will update the URL but not trigger route
          SearchApp.navigate(sortOrder ? "/by-" + sortOrder : "");
        }
      }    
      
      var AppRouter = Backbone.Router.extend({
          index: function(str, sort) {
            if(sort) {
              this.searchModel.sort(sort);
            }
          }
      }); 
      

    Notice also that I changed the view.el declaration just to #order, and refer to the element with this.$el instead of a jQuery selector. These are unrelated, but still best practices.

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

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
Configuring TinyMCE to allow for tags, based on a customer requirement. My config is
I've got a string that has curly quotes in it. I'd like to replace
I am doing a simple coin flipping experiment for class that involves flipping a
I am trying to render a haml file in a javascript response like so:
I would like to run a str_replace or preg_replace which looks for certain words
We're building an app, our first using Rails 3, and we're having to build

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.