Watching a service's attribute from within a route in the EmberJS framework

There seems to be a concept that I'm struggling to grasp here. To my understanding, any instance of Ember.object should be able to observe properties on another instance of Ember.object.

In my scenario, there is a service, a router, and a component involved. The requirement is for the component and the router to observe a property on the service. It's possible that I might not have structured the solution correctly, so I will outline what I'm attempting to achieve at the end.

This is essentially what I currently have:

/services/thing-manager.js

export default Ember.Service.extend({
  observedProperty: 'original value'
});

/components/thing-shower.js

export default Ember.Component.extend({
  thingManager: Ember.inject.service(),
  myObserver: Ember.observer(
    'thingManager.observedProperty',
    function() {
      // This console log works as expected, unlike the one in the routes
      console.log('THING SHOWER COMPONENT observed change on thingManager')
    }
  ),
 actions: {
   changeObservedProperty: function() {
     let thingManager = this.get('thingManager')
     let newText = thingManager.get('observedProperty') + '!'
     // Ensure to call `set` to trigger observers
     thingManager.set('observedProperty', newText)
   }
 }

});

/routes/things.js

export default Ember.Route.extend({
  thingManager: Ember.inject.service(),

  underObservation: Ember.observer('thingManager.observedProperty', function() {
    // Expected console output that doesn't happen
    console.log('THINGS ROUTE observed change on thingManager')
  }),
});

It can be seen that I anticipate receiving console output from both observers in the component and router. However, why isn't this working?

Link to Twiddle!

Main Objectives

This could potentially be a separate inquiry, but I am interested in finding out if there is a more efficient way to achieve my goals. I've been introduced to the 'data down, actions up' concept, which has guided my current approach. The objective is to develop a website that loads a JSON file containing various GPS coordinates and displays them on a map.

The aim is to click on a map marker and have it load corresponding data, ultimately altering the route. Therefore, I thought about maintaining my markers within a service, where a change in the selected marker would be observed by the router for transitioning to the next route. Simultaneously, the component would detect the property change and update the map accordingly.

Thank you all!

Answer №1

If you haven't utilized the thing-manager service in your route file things.js, the observer will not be triggered.

The code snippet in routes/thing.js:

init(){
    this._super(...arguments);
    this.get('thingManager');
},

By introducing this, your observer will be fired.

In my opinion, if you are following the DDAU principle, then your component should not directly change the properties of the thing-manager service. Instead, it should send actions to the service and let it handle the mutation.

Keep in mind: Observers and computed properties can be used within any Ember.Object, including the thing-manager service.

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

Preventing users from accessing the previous page via the browser back button after logging out in an AngularJS application

Currently, I have developed an angularjs web application and facing a challenge. After logout, I am looking to prevent users from navigating back to the previous page using the browser's back button. Ideally, I would like to display a customized messa ...

Error: JSON input ended unexpectedly and was not caught in the promise block

This code snippet showcases the add to cart functionality, which involves inserting data into a database. Although the database insertion works correctly, an error occurs every time the "add to cart" button is clicked (despite still successfully adding to ...

ReactJS component experiencing issues with loading images

In my React project, there is a directory containing several images, and I am attempting to import them all into a carousel using Bootstrap. The current code looks like this: import Carousel from 'react-bootstrap/Carousel'; const slideImagesFold ...

Is it possible to access a sub property using a dot string in Vue 3?

Given a Vue 3 proxy object structure as shown below: <script> export default { name: "test", data() { return { users: [{ "id": 1, "name": "Leanne Graham", " ...

If an element exists in one of the dimensions of a multi-dimensional array

I am facing an issue with my 2D array structure. Here is an example of how it looks: `var arr = [["1", "2", "3"], ["4", "5"], ["6"]];' Despite having the value "4" in one of the inner arrays, when I try running $.inArray("4", arr); or arr.indexOf("4" ...

Sorting feature fails to function properly when used in combination with pagination and

<table> <thead> <tr> <th class="col-md-3" ng-click="sortDirection = !sortDirection">Creation Date</th> </tr> </thead> <tbody> <tr dir-paginate="item in items | filter:itemFilter | items ...

Route.get() is looking for a callback function, but instead received an [object Promise]

Currently, I am in the process of developing a REST API using express and following the architecture outlined in this particular article. Essentially, the setup involves a router that calls a controller. Let me provide you with an example of how a call is ...

How to disable or enable a submit button in jQuery 1.8

Recently, I upgraded from jquery version 1.5.2 to 1.9 and encountered an issue with my disabled buttons not functioning properly. The buttons should become enabled after the form fields are filled out, allowing the user to either remove or save the infor ...

JavaScript switch statement and case expression

Struggling to use boolean expressions within a switch statement to search for undefined values and manually change them. When using an if statement, the process is easier. For example: if statement if(Item1 == undefined) { item1 = "No"; } else if (Item ...

Creating an HTML element that can zoom, using dimensions specified in percentages but appearing as if they were specified in pixels

This question may seem simple, but I have been searching for an answer and haven't found one yet. Imagine we have an HTML element with dimensions specified in pixels: <div style="width:750px; height: 250px"></div> We can easily resize i ...

"Creating a dynamic Map using the HERE Maps API and adjusting its size: A step-by-step guide

I am currently working on a Website project and I am interested in incorporating an interactive map from HERE Maps that spans the entire screen under my navigation bar. How can I achieve this? After initially using Google Maps, I switched to HERE Maps due ...

Enabling Bootstrap modal windows to seamlessly populate with AJAX content

I'm currently in the process of crafting a bootstrap modal that displays the outcome of an AJAX request. Below is my bootstrap code: {{--Bootstrap modal--}} <div id="exampleModal" class="modal" tabindex="-1" role="dialog"> <div class="m ...

Looking to reduce the size of a logo image within a container as you scroll down a webpage?

I've been working on creating a logo section for my website, but I'm struggling to make it shrink as users scroll down and expand back to its original size when they scroll up. I've tried various JavaScript and jQuery functions without succe ...

Exploring the capabilities of the Next.js router and the useRouter

import { routeHandler } from "next/client"; import { useRouteNavigator } from "next/router"; const CustomComponent = () => { const routerFromHook = useRouteNavigator(); } export default CustomComponent; Can you explain the disti ...

Tips for transforming a Vue 2 website into a progressive web application (PWA) were requested

As I explored the PWA functionality in Vue 3, I noticed that it is not available in Vue 2. If anyone has any insights on how to successfully convert a Vue 2 project into a PWA, I would greatly appreciate your input. Thank you! ...

I am experiencing some issues with my AngularJS JavaScript code. The root scope is updating correctly, but the other two scopes are not working as expected. Can

My attempt at writing AngularJS JavaScript code seems to be malfunctioning. While the root scope updates properly, the other two scopes FirstCtrl and SecondCtrl do not update as expected when the root scope is updated. I would like all three scopes to upd ...

Can the orientation of the card reveal be customized in Materializecss?

Exploring the card-reveal feature in the materializecss framework on this page: https://codepen.io/JP_juniordeveloperaki/pen/YXRyvZ with official documentation located at: In my project, I've rearranged the <div class="card-content"> to display ...

Issue with VueJS where the datalist input does not reset the value

I am currently working on a Vue component that scans QR codes and adds information to a database upon successful scanning. The scanning process works perfectly fine. However, after successfully sending the data, I need to clear the input field in my datali ...

Secure your website with the latest JWT cookie security measures

After storing a JWT with an expiry date set 30 days ahead, the question arises - is it secure to store this JWT in a cookie? The aim is for the token to persist beyond a single session, much like the "Keep me logged in" feature found on some websites. Se ...

Substitute this.bindMethod for function component

I have a class component that is structured like this: interface MyProps { addingCoord: any resetCoords: any } interface MyState { x: any y: any } class DrawerOld extends React.Component<MyProps, MyState> { width: number height: number ...