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

Is there a way to incorporate the ACE code editor into a Vue project without relying on its built-in Vue

Just starting out with Vue and I'm looking to incorporate the ace code editor (this package) into my project. However, I want to avoid using the vue2-component & vue3-component versions for learning purposes. How can I achieve this? What's t ...

What steps should be taken to enable the "You and moderator can reply" feature in a bot when sending proactive messages to channels?

A project I am currently working on involves creating a bot that sends proactive messages to channels. The client has requested that I include options like No reply or You and moderator can reply with the messages posted by the bot proactively. Here is wh ...

What could be causing my Material UI Divider to appear invisible within a Material UI Container or Paper component?

Hey there! I am absolutely smitten with Material UI - it's incredibly versatile. However, I'm facing a bit of trouble with the Material UI Divider not displaying when nested within either a Container or Paper component. I've looked into it ...

The background image of my bootstrap carousel is not responsive to changes in the browser window size

Hey there, I'm new to the world of programming and currently working on a project to create the front end of my personal website. I've opted to utilize a bootstrap carousel background image slider in my index.html file. However, I've noticed ...

Determining the class condition using AngularJS ng-class

I am working with an HTML element that contains AngularJS directives: <div class="progress"> <span ng-repeat="timeRangeObject in timeRangeObjects" style="width: {{timeRangeObject.percentage}}%" ...

Aligning a DIV using javascript

Hey everyone, I'm encountering an issue with the JavaScript on my website. I'm struggling to center the div in order to properly display the image I click on. It seems to work fine on the second attempt, but on initial click, the div always appea ...

Tips for inserting a component into a div selector using Angular 2

Could someone please help me figure out how to inject a component into a div selector using a class or id? I'm familiar with injecting components into other components, but not sure how to do it specifically within a div. Any guidance would be greatly ...

Dealing with multiple POST requests at once in Node Express JS - Best Practices

I've been working on a Node project with Express to handle incoming GET/POST requests. I have set up routes to manage various types of requests. One specific route, /api/twitter/search, calls a function that uses promises to retrieve Twitter feeds and ...

Error message: "Module not found" encountered while executing test case

I am a beginner in node and nightwatch and I have followed all the initial instructions from setting up node, npm, selenium standalone, starting the selenium driver. I also downloaded the chrome driver and placed it in the same directory. I created the con ...

How to Delete Multiple Rows from an Angular 4 Table

I have successfully figured out how to remove a single row from a table using splice method. Now, I am looking to extend this functionality to remove multiple rows at once. html <tr *ngFor="let member of members; let i = index;"> <td> ...

Is it best practice to use the AngularFirestoreCollection for updating Firestore items in AngularFire?

Within my application, I have a list that necessitates the use of an "or" condition. However, according to the documentation: "In this case, you should create a separate query for each OR condition and merge the query results in your app." Consequently ...

Managing the automatic download of a zip file through JQuery - A guide

When working with a REST API and creating a zip file for forced download, the task is to call the API by sending necessary POST data through JQuery to initiate the download. How can this goal be accomplished effectively? ...

What is the best way to export image paths using require() from a single index.js file in a React Native project?

I am looking for a way to efficiently export all images from a single file named index.js, so that in the future, if I need to change the path of an image, I only have to make changes in one file. For example: export {default as avatar} from './avata ...

Guide on parsing and totaling a string of numbers separated by commas

I am facing an issue with reading data from a JSON file. Here is the code snippet from my controller: myApp.controller("abcdctrl", ['$scope', 'orderByFilter', '$http', function ($scope, orderBy, $http) { console.log('abc ...

Filtering dynamically generated table rows using Jquery

I'm currently working on a project that involves filtering a dynamic table based on user input in a search bar. The table contains information such as name, surname, phone, and address of users. Using jQuery, I have created a form that dynamically ad ...

Which is the better option for opening a link in a button: using onclick or href?

What is the most effective way to open a link using a button? <button type="button" onclick="location='permalink.php'">Permalink</button> <button type="button" href="index.php">Permalink</button> ...

Absence of property persists despite the use of null coalescing and optional chaining

Having some trouble with a piece of code that utilizes optional chaining and null coalescing. Despite this, I am confused as to why it is still flagging an error about the property not existing. See image below for more details: The error message display ...

Initially, the 'display none' CSS command may not take effect the first time it is used

I am currently working on a slideshow application using jquery.transit. My goal is to hide a photo after its display animation by setting the properties of display, transform, and translate to 'none' value. Although the slideshow application work ...

After attempting to refresh the webpage with the F5 key, I noticed that the jQuery progress bar was not functioning properly. Additionally, the webpage failed to display any

Trying to implement a web loading bar using jQuery on my website was initially successful, but I encountered an issue when reloading the page with F5. The progress bar would not work and the webpage displayed only a white background. Below is the code snip ...

Uploading files seamlessly without the need for refreshing the page

On my HTML page, I have a form input that allows users to upload a file. Here is the code snippet: <form action = "UploadFile.jsp" method = "post" target="my-iframe" enctype = "multipart/form-data"> <input type = "file" name = "file" ...