In Backbone.js, specialized events are dispatched to cater to unique needs

In search of a sleek JavaScript animation to have some balls gracefully moving within a canvas, I aim to implement collision detection using custom events managed through Backbone.js rather than resorting to an intricate nested loop to monitor interactions between ball pairs.

var j;
for (j = 0; j < N_BALLS; j++) {
    ball_center = new Point(..., ...);
    ball_shape = new Circle(ball_center, ball_radius);
    ball_velocity = ...;
    ball_ID = j;
    balls[j] = new Ball(ball_shape, ball_velocity, ball_ID);
    _.extend(balls[j], Backbone.Events);
    balls[j].on("imhere", balls[j].event_handler);
}

function animate() {
    if (!paused) {
        context.clearRect(0, 0, canvas.width, canvas.height);
        var j;
        for (j = 0; j < N_BALLS; j++){
            balls[j].updatePosition();
            balls[j].trigger("imhere", balls[j].shape, balls[j].ID);
        }
        for (j = 0; j < N_BALLS; j++)
           balls[j].draw(context, '#0000ff');
        window.requestNextAnimationFrame(animate);
    }
}

The event_handler serves as a method within each Ball object

Ball.prototype.event_handler = function(shape, ID) {
    console.log("ball " + this.ID + " caught message from ball " + ID);
};

With the hope that occasionally one ball will intercept a message from another, unfortunately, such occurrences are never observed.

The desire is to structure things in a manner allowing the event handler to:

  • pass on the event when this.ID == ID
  • halt event propagation if this.ID != ID

Answer №1

Implementing Backbone Event Handling

this.ID may be undefined due to the context parameter requirement in Backbone's .on() method, unless specified elsewhere manually.


Registering and triggering events directly on the Ball object is not recommended as events are not globally accessible within Backbone. Consider implementing an event bus or aggregator.

Creating a simple global event channel can be done like this:

var GlobalEvents = _.extend({}, Backbone.Events);

While Backbone itself extends Backbone.Events, it's more efficient to create a local event channel specific to your requirements.


Instead of extending every instance of a Ball, extend the prototype once for better performance:

_.extend(Ball.prototype, Backbone.Events);

Use listenTo over on for better memory management.

When destroying a ball, calling ball.stopListening() avoids memory leaks and addresses context issues within event handlers.

To implement with a global event aggregator:

balls[j].listenTo(GlobalEvents, "imhere", balls[j].event_handler);

Remember, Backbone events differ from DOM events and do not support methods like stopPropagation or preventDefault.


Optimizing Collision Detection

Evaluating collision through events may not be ideal. Consider utilizing a dedicated collision detection function like isCollindingWith(ball) during position updates.

An in-depth guide on 2D collision detection explores advanced techniques such as spacial data structures like Quad Trees and R-Trees.

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

What are the steps to store a firebase storage downloadURL in a firestore collection?

I'm facing an issue with saving my firebase storage image into a firestore collection variable. Initially, it was working correctly but suddenly stopped functioning, and now the image variable is returning null. Note: I am using the asia-south1 serve ...

How can I organize the selected options from a select2 form element using a basic sorting method?

I am utilizing select2 by ivaynberg and encountering an issue with the data arrangement upon submission. Is there a method to have the results in the form submit data reflect the order in which they were selected in the select2 element, without relying on ...

I'm curious if it's possible to modify a webpage loaded by HtmlUnit prior to the execution of any javascript code

To begin, I want to elaborate on the reasoning behind my question. My current task involves testing a complex web page using Selenium + HtmlUnit, which triggers various JavaScript scripts. This issue is likely a common one. One specific problem I encount ...

A guide on effectively utilizing the Map datatype in JavaScript

Recently, I've started delving into the world of es6 Map due to its unique features, but I have some reservations regarding pure operations. For example, when removing properties from objects, I usually use the following function: function cloneOmit ...

Issue with child rows not functioning properly in DataTables when utilizing Datetime-moment

I've successfully integrated this data into live.datatables.net and almost have it running smoothly. However, I am encountering an issue with displaying the last detail as a child element. The final part of the row should be shown with the label "Mes ...

Guide on transforming a PHP array encoded in JSON into a JavaScript array

After fetching a JSON encoded array via AJAX from a PHP file, I need to manipulate it as an array in JavaScript. How can I achieve this? Here is my AJAX call to the PHP File: $.ajax({ type:"POST", url:"ajaxfetch.php", success:function(re ...

Tips for creating a personalized dialog box after logging in with React Admin based on the server's response

One of my requirements is to allow users to select a role during the login process. Once the user enters their username and password, the server will respond with the list of available roles. How can I implement a dialog where the user can choose a role fr ...

Tips for invoking an asynchronous function within an if condition?

When trying to maintain variables in the background.js of a Chrome extension, I encountered difficulties that require me to reinitialize some global variables. Here is the code snippet (view fiddle) I am using to demonstrate the issue: var temp = null; ...

The functionality of the combobox in Vuetify differs from that of an input field

I have implemented Vuetify and am using its combobox component for search functionality on my website. However, I have noticed that the text value in the combobox only gets added to the watcher when the mouse exits the field. This behavior is not ideal f ...

Difficulty encountered with document.querySelectorAll retrieving paginated elements

I am currently developing a project called STEEP. Our implementation involves utilizing infinite scroll to load 8 videos at a time as the user scrolls through the page. However, we are facing an issue with the script responsible for handling video playbac ...

Implementing asynchronous loading of an image onto a webpage using JavaScript

Is it possible to asynchronously load an image specified in the src attribute of an HTML image tag? I am trying to invoke a Java class using an image src tag, but I want this to happen asynchronously without affecting the current functionality of the web ...

Exploring ways to traverse a JSON encoded object in PHP with the help of JavaScript

I am facing an issue while trying to access my data from PHP. I am using the following code: echo json_encode($rows); When I comment out datatype: 'json', I can see a normally encoded JSON string. But when I use it, the alert shows me an array ...

Implementing relative pathing in front-end development while using ExpressJS for the back-end

I'm currently in the process of developing an application with Express 4.14. When it comes to routing, I have a situation where the incoming request is "https://example.com/page", and I am using res.sendFile(__dirname + "/../client/pages/page/index.ht ...

Currently, only the initial button is functional. I am uncertain if it is due to a script issue or if there is a rule that I inadvertently

As a beginner, I am eager to grasp the fundamentals and rules of Javascript. My goal is to create a basic example that involves a box with three buttons. However, I have encountered an issue where only one button seems to be functional despite having dis ...

Display or conceal form elements depending on the JSON response

Upon making an api call, a json Response is received with the following structure: {"Field":"Amount","FieldName":"Amount","FieldType":"Numeric","MaximumLength":128,"MinimumLength":0,"Options":"Mandatory"} This api call yields between 5-10 of these object ...

Redirecting script upon successful connection detection

I have created a script that checks for internet connectivity using an image, and redirects if internet is available. However, the issue is that it caches the images, leading to attempts to load them even when offline. Is there a different approach I can ...

There was a problem retrieving the product information from the API

I have been struggling to pinpoint the exact issue at hand. The foundation of HTML and CSS is pre-written, with JavaScript responsible for generating the core elements to populate the DOM. Within my script, I am attempting to retrieve product data in ord ...

trigger a function when the iframe is altered

I am currently working on creating a function that can process credit card payments using an iframe. The challenge I am facing at the moment is dealing with error messages appearing in a less than ideal manner. Photo: I have been attempting to capture the ...

Navigating to the next or previous item in an Angular2 Firebase collection based on the current key

In my photo gallery, I have the key of an item in firebase and would like to enable users to navigate to the next or previous picture by pressing buttons. In a non-Angular2 context, I might use the following code snippet to retrieve the next item: ref.ord ...

Guidelines for attaching a div to the bottom of a page?

I have a navigation menu inside div.wrapper, and I am trying to make the div.wrapper stick to the footer. <div class="wrapper"> <div id="menu"> <ul> <li>1.</li> <li>2.</li> ...