Backbone.js is dispatching 'add' event only once

To gain a better understanding of Backbone.js, I decided to create a mock blog using Backbone.js. I added a 'create post' button that triggers the following code when clicked:

posts.create({title: makeid(),content: makeid()})

(makeId() generates random characters.)
When a post is created, it should dispatch an add event that I am listening for. However, the add event only fires once and I can't figure out why. I have inserted multiple console.log statements in the code to display my attempts. On the server side, I return all the models on creation but couldn't find documentation about what the server should return. This is the content of app.js:

$(function(){

    var Post = Backbone.Model.extend({
        defaults:{
            id: '',
            title : 'Untitled',
            content: 'No content'
        }, 
        urlRoot : '/posts/'
    });

    var Posts = Backbone.Collection.extend({
        model : Post,
        url: '/posts/'
    });

    var posts = new Posts;

    var PostView = Backbone.View.extend({
        tag: 'li',

        template: _.template($("#post-template").html()),

        events: {
            "click .delete-post" : 'deletePost'
        },

        initialize: function(){
            //this.listenTo(this.model, 'change', this.render);
            this.listenTo(this.model, 'destroy', this.remove);
        },

        render: function(){
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        },
        deletePost: function(){
            console.log(this.model);
            this.model.destroy();
            this.$el.remove()
        }
    });

    var AppView = Backbone.View.extend({
        el : $("#home"),

        events:{
            "click #add-post": "addPost"
        },

        initialize: function(){
            this.listenTo(posts, 'add', this.addOne);
            posts.on("add", function(post){
                console.log('post added: ' + post);
            });
            posts.fetch({ update: true });
        },

        addPost:function(){
            console.log('add post')
            posts.create({
                title: makeid(), 
                content: makeid()
            },{success: function(){console.log('success');}
            });
        },

        addOne: function(post){
            console.log('one was added');
            var view = new PostView({model:post});
            this.$("#posts").append(view.render().el);
        },

        render: function(){
            if(posts.length){
                console.log('rendering');
            }
        }
    });
    var appView = new AppView;
});

function makeid()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

This is the structure of index.html:

<!doctype html>
<html>
<head>
    <title>Backbone test</title>
    <link rel="stylesheet" type="text/css" href="/static/css/bootstrap.min.css">
</head>
<body>


<div class="container">
    <div class="row">
        <div class="span6" id="home">
            <a href="#" id="add-post" class="btn btn-mini btn-success">add post</a>
            <ul id="posts">
            </ul>
        </div>
    </div>
</div>


<script src="/static/js/jquery.js"></script>
<script src="/static/js/underscore.js"></script>
<script src="/static/js/backbone.js"></script>
<script src="/static/js/bootstrap.js"></script>
<script src="/static/js/app.js"></script>




<script id="post-template" type="text/x-handlebars-template">
<div class="span4">
    <h3>
        <%- title %>
        <br />
        <a href='#' class='btn btn-mini btn-primary'>edit</a>
        <a href='#' class='btn btn-mini btn-danger delete-post'>delete</a>
    </h3>
    <p><%- content %></p>
</div>
</script>

</body>
</html>

Answer №1

  • In a Backbone collection, duplicate models with the same id are not allowed.
  • If your models have an empty string as the default id, any value other than undefined or null will result in the same behavior.
  • When the server returns models without an explicitly set id, the default one is used instead.

The issue arises when the first model created uses the default id and gets added to the collection. Subsequently, when creating a second model, it also has the default id, preventing it from being added to the collection. You can see a demonstration at http://jsfiddle.net/nikoshr/vfEVC/.

To resolve this, either remove the default id or assign a unique one on the server side for both instances to be included in the collection.

For more information, visit http://jsfiddle.net/nikoshr/vfEVC/1/

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

Animation is frequently interrupted by hidden overflow

My query may be a bit complex, but I will do my best to explain. I have created an animation on my webpage where there is a <div> with the property of overflow: hidden. The animation pauses at this point for a few seconds before resuming. Any suggest ...

Demonstrating how to showcase information from an API array in a Node.js application and render it as a

I am aiming to showcase information retrieved from the API on my pug page, specifically displaying the names of car parks. Below is the code from Index.js var request = require('request'); var express = require('express'); var ...

Leveraging functionality from an imported module - NestJS

Currently, I am utilizing a service from a services module within the main scaffolded app controller in NestJS. Although it is functioning as expected - with helloWorldsService.message displaying the appropriate greeting in the @Get method - I can't ...

The refresh function in next/navigation's router is not functioning properly

In my component, I have an onSubmit function that should reload the page every time a task is added. However, despite not receiving any errors in the console and even sending the toast message, the page is not refreshing after the function is called. " ...

Using 'if' conditions in Reactjs: A step-by-step guide

Working with Reactjs in the nextjs framework, I have received user data that includes the "category name (cat_name)" selected by the user. Now, I need to display that category in a dropdown menu. How can I achieve this? The current code snippet showcases ...

Importing a substantial number of records from an XML file into an HTML table

Currently, I am working on a project where I am reading records from an XML file and dynamically displaying them in an HTML table using JavaScript's push method. Everything works smoothly when the number of records is below 1000. However, when the num ...

How can I prevent my mouse click from being overridden by my mouse hover?

Currently, I am developing a Sudoku game using JavaScript and facing some challenges with mouse events. My goal is to enable users to hover over a square and have it change color, as well as click on a square to highlight the entire row, column, and quadra ...

What sets apart optionalDependencies from peerDependencies in the Meta optional?

Why are both marking dependency as optional and what is the specific use-case of each? Is peerDependenciesMeta intended for npm packages while optionalDependencies is meant for projects? For example, in my npm package, certain modules require dependency ...

Create a selection menu in an HTML dropdown list using unique values from a JSON object that is separated by commas

I'm working with a JSON object that contains multiple key value pairs, one of which is the Languages key. This Languages key holds comma-separated values such as "English, Hindi, French," and so on. My goal is to extract distinct values from the Lang ...

Ensure that the code is functioning properly for each element and is tailored to its specific date

Trying to implement a countdown using JavaScript and HTML elements. The code is functional, but encountering an issue with three items in the code: <div class="col-xl-4 col-md-6"> <article> <div class=&qu ...

Suggestions for customizing this comparison function for sorting tables

When sorting alphabetically, I want to prioritize anything that begins with [ or . before the rest. How can this be achieved? function ts_sort_default(a,b) { aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]); bb = ts_getInnerText(b.cells[SORT_COLUMN_ ...

Toggle the mute and unmute feature for a participant in an AWS Chime meeting

Hello everyone! I'm looking for details on the AWS Chime SDK (amazon-chime-sdk-js). Is it possible with the Amazon Chime SDK for 3 participants (Anna, John, and Lenny) in a meeting room to have Anna ignore Lenny's microphone and only hear John, ...

The Firebase Authentication module encountered an uncaught error: [$injector:modulerr]

I encountered a challenge while developing a small task for Gmail user login and logout using Firebase authentication. The issue in my code is Uncaught Error: [$injector:modulerr] The libraries I included are: <script src='https://cdn.firebase.co ...

Utilizing XMLHttpRequest alongside a node.js server running on the Express framework

There seems to be an issue with using XMLHttpRequest on my local server created in Node.js and Express, for reasons unknown. Let me illustrate the problem... Here is the Node.js server code: var express = require('express'), app = express.creat ...

Does Next.js pre-render every page, or does it only pre-render the initial page?

As I dive into the world of nextjs, I'm coming across conflicting information. Some sources claim that nextjs only prerenders the first page, while others suggest that all pages are prerendered by default. This contradiction has left me confused about ...

Formatting XUL elements to fit within specified line lengths

Consider the scenario below: <groupbox id="keyboard" orient="horizontal"> <button id="a" label="a" class="thinbutton"/> <button id="b" label="b" class="thinbutton"/> <button id="c" label="c" class="thinbutton"/ ...

BoxHelper causes BoxGeometry to become enormous

UPDATE Upon further investigation, I discovered that the issue with the oversized box occurs specifically when I attempt to incorporate the HelperBox. To demonstrate this problem, I created a JSFiddle, where the second box's size remains unaffected. ...

How can you use yargs (npm package) to generate an error message when a command is not recognized?

Is it possible to have yargs with 2 commands? yargs .command('test-all','',handler) .command('test-file','',handler) .argv When the user inputs: node myapp.js other-command No error is thrown by yargs. What steps s ...

Instructions for configuring AngularJS as the view engine in ExpressJS

I recently started working on an Express project where Jade is set as the default view engine in the app.js file: // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); ...

Leveraging ajax to transmit a JavaScript array to a codeigniter controller for seamless integration with a specific function

My form has a submit button that, when clicked, adds specified elements to an array. $("#submitButton").click(function(){ var selection = $("#selectedList li"); var familiesSelection = []; selection.each(function() { familiesSelection. ...