Trigger a function following a collection update in Angular Meteor

I am in the process of developing a multiplayer game, and I would like a specific function to be triggered once the first player updates an "isStarted" field in the collection.

Within my controller code:

angular.module('mcitygame').directive('gcaseGame', function() {
return {
    restrict: 'E',
    templateUrl: 'client/gcases/gcase-game/gcase-game.html',
    controllerAs: 'gcaseGame',
    controller: function($scope, $stateParams, $reactive, $window, $element) {

        $reactive(this).attach($scope);

        this.subscribe('gcases'); // Keep track of changes in the collection related to the "isStarted" field

        this.helpers({
            gcase: () => {
                return GCases.findOne({_id: 'dynamicID'}) //For illustration purposes, I have used 'dynamicID' instead of $stateParams.gcaseId obtained from the router.
            });

        this.startGame = function(option){
            if(option == 1) {
                console.log(" Users clicked me from the interface!");
                GCases.update({_id :'dynamicID'}, {
                    $set: {isStarted: true, updatedAt: Date.now()}
                });
            } else {
                console.log("I am here because someone called me from a different client!");
            }

        };

        ////////////////////////// I want to implement something like this
        this.autorun(() => { 
            if(this.gcase.isStarted){
                console.log(" isStartred = " + this.gcase.isStarted);
                this.startGame();
            }
        });
        ////////////////////////// or this
        this.gcase.observeChanges({
            changed: function (id, gcase) {
                console.log(" isStartred = " + this.gcase.isStarted);
                this.startGame();
            }
        });
        //////////////////////////

    }
}})

Furthermore, outside the controller:

GCases = new Mongo.Collection("gcases");

Any assistance on this matter would be greatly appreciated.

Answer №1

One way to enhance your update function is by implementing a callback function.

Answer №2

Here's the approach I took to tackle this issue:

    const self = this; // Assigning 'this' to a variable since it needs to be accessed inside 'observeChanges'
    GCases.find({_id:'dynamicID'}).observeChanges({ // Using 'that.gcase' as suggested resulted in an error stating that it's not a function
        changed: function (id, gcase) {
            console.log(" isStartred = " + gcase.isStarted);
            self.startGame(2); // Inputting any value other than 1 triggers the 'else' condition, and the log will only display on other clients' consoles
        }
    });

This method effectively resolved the issue for me. While there may be alternative approaches, I hope you find this solution useful.

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

Meteor: The JSON does not align with the SimpleSchema

I have implemented a SimpleSchema for a collection in my meteor-app Collection.attachSchema(new SimpleSchema({ title: { type: String }, slug: { type: String, unique: true }, language: { type: St ...

How to eliminate unnecessary space when the expansion panel is opened in material-ui

Is there a way to eliminate the additional space that appears when clicking on the second accordion in material UI? When I open the second accordion, it shifts downward, leaving a gap between it and the first accordion. Any suggestions on how to remove thi ...

Using the factory pattern in a Node.js (Express) application

As I delved into the realm of design patterns, I found myself drawn to the factory pattern. However, as I perused through code written by others, I noticed that this particular pattern wasn't as prevalent, especially in newer stacks. Take for example ...

The appropriate method for showcasing cards within lists, such as in the platform Trello

I'm in the process of developing a project similar to Trello, but I'm facing some challenges on how to proceed. Initially, I created an 'init' function within my AngularJS Controller to handle HTTP requests: $scope.loadLists(); ...

Arrange pictures and div elements in a horizontal layout

I am facing an issue with my code that is displaying 5 'cards' in a messed up layout instead of a straight line. I have tried to align them vertically, but some are still higher and not in the right positions. For reference, I want the layout to ...

Access the HTML file from a different directory

I have a directory called "myWebsite". Within this directory, there is a file named "index.html" and another subdirectory named "other". Inside the "other" directory, there are CSS files, JS files, and "page2.ht ...

Generating HTML widgets dynamically with jQuery: A step-by-step guide

Looking for a way to display an interactive widget on your page while allowing users to generate multiple instances and interact with them simultaneously? Imagine having a widget like this: <div id="my_widget"> <script type="text/javascript" ...

Acquire by Identifier - Tonic()

Currently, I am in the process of setting up a code example on tonicdev.com for my open-source React component available on Npm. Below is the code snippet that I am attempting to execute (editable live on tonicdev.com here): var React = require('rea ...

Determine the duration/length of an audio file that has been uploaded to a React application

I am working on a React web application built with create-react-app that allows users to upload songs using react-hook-forms. The uploaded songs are then sent to my Node/Express server via axios. I want to implement a feature that calculates the length of ...

"When attempting to pass a string into the res.send() method in Node.js, undefined

As a new Node.js user, I'm attempting to send data back to the browser by utilizing a function called load_blocks() from an external file that I created, and then calling it with res.send(). I currently have two basic files in my setup: The first on ...

Using JavaScript Functions to Resize Buttons and Change function on Click

I have a button in my code that triggers CSS changes by adding and removing classes. The JavaScript for this function works as intended - clicking once adds the class, clicking again removes it, and so on. However, I also implemented a feature to remove t ...

Leveraging Ajax for Executing a MySQL Query in PHP upon Clicking the Facebook Like Button

Is it possible to execute a MySQL query whenever a Facebook Like button is clicked on a webpage? I am aware that FB.Event.subscribe('edge.create', function(response) {} is used for such actions. However, my lack of knowledge in Javascript and AJA ...

Discover the method to retrieve every element from a Listbox with the click of a Button and utilizing an ajax call

How can I retrieve all the elements from a Listbox when a Button Click event triggers an ajax call? I have created a function that successfully returns all the elements from the Listbox. However, when I try to bind it with the ajax call, it doesn't w ...

What is the best way to activate a CSS animation?

I've hit a roadblock while attempting to trigger a CSS animation. Here's my CSS: h3[id="balance-desktop"]{ color: black; -webkit-animation-name: gogreen; -webkit-animation-duration: 2s; animation-name: gogreen; animation-du ...

What is the best way to pass a websocket instance to Vue.js components and then invoke the send() method on it?

I am attempting to send a message via a web socket to the server when a button is clicked: // HelloApp.vue <template> <div class="hello"> <h1>{{ msg }}</h1> <button v-on:click="sendMessage($event)">Send Message< ...

What exactly does the combination of {on, attrs} create within Vue/Vuetify?

Although this question may have been asked before, I am still struggling to grasp its meaning. Can you help me understand it better? <v-dialog v-model="dialog" width="500" > <template v-slot:activator=&quo ...

What is the best method for displaying plain text using the br tag?

My component looks like this: class News extends Component { state = { isSimple: this.props.isSimple } render() { return ( <div> <div className="extended">extended</div> simple text </div&g ...

Optimal method for linking NodeJS and Angular in a seamless integration

I am currently working on developing a web application that integrates a Node server as the backend and Angular for the front end. At the moment, my application consists of two JavaScript files: server.js and controller.js. Below is the code snippet for ea ...

Dealing with a 404 Error in Node.js and Express Routing

After successfully creating a Node/Express app tutorial earlier, I encountered issues when trying to replicate it for a new project on both Ubuntu and Windows. The basic routing consistently fails and results in 404 errors, which is incredibly frustrating! ...

Troubleshooting Async Function compatibility between Express and NestJs

Initially, I set up a small express server to handle report generation and file writing tasks. var ssrs = require('mssql-ssrs'); var fs = require('fs'); const express = require('express') const app = express() const port = 30 ...