Navigating the Spine

Struggling to get routing to function properly in Backbone, I have tried my best but it still seems quite confusing. Here is a snippet of what I currently have:

    routes: {
        ''            : 'home',
        'home'        : 'home',
        'departments' : 'departments',
        'employees'   : 'employees',
        'requests'    : 'requests'
    },

    home: function(){
        new app.HomeView();
    },

This code resides within my router and of course, I call Backbone.history.start(). In my view, I adhere to the pattern of defining a render function and calling it from the initialize method.

    el: '#containerList',

    template: Handlebars.compile( $('#home-template').html() ),

    initialize: function(){         
        this.render();
    },

    render: function(){
        this.$el.html( this.template());
        return this;
    },

HTML:

<section id='main' class='container'>
  <section id='containerList'></section>
</section>

I am encountering the following issues:

  1. When using the back button, views are getting appended instead of refreshed. A page reload is required to rectify this.
  2. Whenever typing a route into the browser's search bar, I need to refresh the page twice to display the view. The behavior is very erratic, sometimes rendering the views without the associated collections.

I have explored various strategies, such as using events on CloseView or utilizing this.remove when leaving the view. Unfortunately, none of these techniques seem to work for me. Documentation regarding routers in Backbone appears to be scarce.

Answer №1

A good approach would be to create a function that can add or remove the main view of the current route. This way, your router will appear like this:

routes: {
        ''            : 'home',
        'home'        : 'home',
        'departments' : 'departments',
        'employees'   : 'employees',
        'requests'    : 'requests'
    },

    home: function(){
        var view = new app.HomeView();
        this.setMainView(view);      
    },

    setMainView: function(view) {
            this.mainView && this.mainView.remove();
            this.mainView = view;
            this.mainView.setElement($('#main'));
   }

This way, there is no need to define the element of the view upfront. Your view will look more concise and organized like this:

var HomeView = Backbone.View.extend({
    template: Handlebars.compile( $('#home-template').html() ),

    initialize: function(){         
        this.render();
    },

    render: function(){
        this.$el.html( this.template());
        return this;
    }

})

In essence, you have a div container holding the current main view (#main), and for each route function, simply call setMainView to update the view accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why isn't Meteor.call functioning in the stub?

As I delve into the realm of async JavaScript coding, I have encountered a gist that has left me puzzled: https://gist.github.com/dariocravero/3922137 Specifically within client_save.file.js - there are parts of this code snippet that baffle me: fileRead ...

JS: Submitting form data through POST method but fetching it with GET method?

When using PHP to retrieve data, the $_POST method cannot be used; only $_GET. Why is that? Could it be that I am not sending my form data correctly? I assumed that by using request.open("POST"), the form would be processed as a POST request rather than a ...

What is the reason behind the non-exportation of actions in Redux Toolkit for ReactJS?

Currently, I am utilizing @reduxjs/toolkit along with reactjs to create a shopping cart feature. However, I am encountering an issue when attempting to export actions from Cart.js and import them into other files like cart.jsx and header.jsx. The error mes ...

The useCallback hooks persist outdated values when the list is refreshed

Why am I not getting the expected values every time the function onRefresh is called using Hooks? Example when onRefresh is called twice: Expected values: true 0 20 false true 0 20 false Received values: false 0 0 false false 20 20 false Initial st ...

Encountering an issue with eslint-loader in a new VueJS project: TypeError - eslint.CLIEngine is not recognized as

Embarking on a fresh VueJS venture with WebStorm. A brand new VueJS project has been established, NPM upgraded, Vuetify added, and upon server initiation, an error pops up: ERROR Failed to compile with 1 errors ...

Exploring the features of NextJS version 13 with the benefits

Starting from the 13th step, SSR is utilized by default and in order to opt for client side rendering you must specify it at the top like so: 'use client' Currently, my setup involves TypeScript and styled-component integration. Take a look at ...

Can an inner promise in JavaScript not be caught by another promise?

When using promises, I am encountering an issue where the "catch" doesn't seem to catch its child promises. This results in me having to include two instances of the "catch" block. Facility.userHaveAccess(locationObject.created_by, locationObject.fac ...

Using Regular Expressions to eliminate any characters that are not directly adjacent to numbers (beside specific characters)

My function generates a result that looks like this: given output For comparison, consider the example string below: var string = '    111   1   1\n 1111111 1 \n   &nb ...

What is causing the reluctance of my Angular test to accept my custom form validation function?

I'm currently facing an issue with testing an angular component called "FooComponent" using Karma/Jasmine. Snippet of code from foo.component.spec.ts file: describe('FooComponent', () => { let component: FooComponent let fixture ...

Background image that covers the entire screen, div elements that scroll on top of the landing screen initially

As a beginner in the world of coding, I apologize for any simple errors in my attempt. Despite researching this issue, I have not been able to find a precise solution that fits my needs. My goal is to create a full-screen background for the landing page. ...

Implement the useEffect() function to handle the loading of external JavaScript on the client-side, replicating the

I have encountered a challenge while trying to integrate a rich text editor into my NextJS project. Since there are no available React components for this specific editor and it operates solely on the client side, I am required to load the necessary JavaSc ...

Encountered a problem with AngularUniversal prerendering: UnhandledPromiseRejectionWarning: Unable to locate NgModule metadata for 'class{}'

Objective The task may seem lengthy, but it's straightforward! Currently, I am utilizing Angular Universal for Server-Side Rendering (SSR) by following a tutorial. The Universal/express-engine has been installed, main.js is generated in the dist/pro ...

What methods can I use to integrate a Google HeatMap into the GoogleMap object in the Angular AGM library?

I am trying to fetch the googleMap object in agm and utilize it to create a HeatMapLayer in my project. However, the following code is not functioning as expected: declare var google: any; @Directive({ selector: 'my-comp', }) export class MyC ...

Struggling to make dynamically created SVG 'use' elements function properly

SVG offers a unique system with symbol and use where icons can be defined once and reused throughout the SVG using use. However, I am having trouble getting it to work from JavaScript. You can view an example on this JSFiddle link. When programmatically ...

Finding a solution to the type issue of error handling in Route Handler with NextJS

I'm working on a route handler located at app/api/transactions/route.ts. Here's a snippet of the code: import { NextRequest, NextResponse } from "next/server"; import { AxiosError } from "axios"; import axios from "../axi ...

css effect of background image transitioning on mouse hover

Is there a way to have an element on my webpage with a background image that follows the movement of the mouse when hovered over? I want it to be similar to this website: This is the HTML code I currently have: <section id="home" data-speed="3" data-t ...

In React, is it typical to maintain identical values in both state and ref?

When working with my React app, I encountered a situation where I needed to access state values inside setTimeout() and setInterval(). However, due to closures being bound to their context once created, using state values in these functions would not refle ...

Changing the model does not automatically update the visibility of ng-show

I have a fragment of my view that simply displays a loading indicator. Html: <span class="app-loading-container"> <span class="app-loading-animation" ng-show="loading"></span> </span> When I initially load the page, the span ...

Difficulty accessing `evt.target.value` with `RaisedButton` in ReactJS Material UI

My goal is to update a state by submitting a value through a button click. Everything works perfectly when using the HTML input element. However, when I switch to the Material UI RaisedButton, the value isn't passed at all. Can someone help me identif ...

Understanding how to use the 'this' variable in Vue components is essential for efficiently modifying DOM elements. Let's dive into a clarification on the usage of 'this'

Within my vue component, the structure is as follows: export default{ name: '', data: function () { return { var1 :{}, var2 : {}, ... } }, created: function () { this.methodName1() }, methods: { me ...