activating a feature within a component in Ember

As I transition to my new route, I set the reportName property and I want to trigger an AJAX request based on changes in the reportname. The response from the AJAX call contains data that I need to pass to a graph component as a property, which should then trigger a function within the component. However, I am having trouble implementing this. Could you please advise me on what I might be doing wrong? I am new to Ember.

export default Ember.Controller.extend(ApplicationRouteMixin, {
    sessionService: Ember.inject.service('session'),

    nameOfReport: null,  

    postObject: function(){
        return {
            Name: this.get('nameOfReport'),
            Take: 30,
            Skip: 0,
        };
    }.property('nameOfReport'),


    ajaxResponse: function(){

       var restApiHost = serverPath + '/report';
       var postobj=  this.get('postObject');
       var token =this.get('sessionService.session.authenticated.access_token');

        Ember.$.ajax({
            url: restApiHost,
            type: 'POST',
            data: JSON.stringify(postobj),
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            beforeSend: function (xhr) {
                var bearer = 'Bearer ' + token ;
                xhr.setRequestHeader('Authorization', bearer);
                xhr.setRequestHeader('Content-type', 'application/json');
            },
            success: function (data) {
                var graphobj= {
                    data:  data.data,          
                    graphModel: GraphModel.create({
                        graphHeight: "320",
                        graphMargin: [40, 80, 40, 60],
                        xDomain: [1, 10],
                        yDomain: [1, 100]
                    …
                    })};
                 Ember.set(this,'graphobject', graphobj);    
            },

            fail: function () {
                alert('Could not contact server');
            },
        });
    }.property('postObject'),       

    graphobject: function(){
        this.get('ajaxResponse');
    }.property('ajaxResponse'),

});

Pod Template:

<div>
               {{line-graph model= graphobject }} 
</div>

Component:

drawGraph: function() {
        // define dimensions of graph   
        var graphdata = this.get('model.data');
        var graphmodel = this.get('model.graphModel');
...
}.property('graphobject'),

Answer №1

Initially, the line

Ember.set(this,'graphobject', graphobj);
is actually replacing the function stored in the graphobject property -- rendering that function unnecessary.

Moreover, even if the drawGraph property is marked as dirty due to a change in one of its dependent keys (as seen in your code), it will not execute until the property is accessed by some code using get. This could occur during a re-render if the template itself accesses the property, or through an observer or action execution.

To address this, consider making drawGraph observe the graphobject. Furthermore, you may need to call drawGraph upon initialization or insertion:

drawGraph: function() {
    // define graph dimensions
    var graphdata = this.get('model.data');
    var graphmodel = this.get('model.graphModel');
    ...
}.observes('graphobject').on('init')/* or .on('didInsertElement') */,

While most experts advise against observers, without knowledge of what occurs in the drawGraph function, it's challenging to recommend an alternative approach.

If you are updating a property in drawGraph and then displaying that property in a template, consider having drawGraph return the value instead of setting it into another property, and use drawGraph in the template instead of the alternate property. In this case, keep drawGraph as a computed property instead of an observer.

If you are utilizing jQuery to manipulate the DOM within drawGraph, and template manipulation isn't feasible for certain reasons, then employing an observer may be necessary.

Upon further examination of your code, it appears that ajaxResponse should also be observed. However, once again, avoid over-reliance on observers. Consider when it is appropriate to make an AJAX request and re-render the graph. Simply changing the report name might not necessitate an update. Perhaps triggering the request and rendering upon specific user actions like "save" or "view" would be more suitable. It ultimately depends on the structure of your application.

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

utilizing javascript to compare the data in a gridview with the value entered in a

I am looking to compare the values entered in my textbox with the existing values in a gridview. I have achieved this on the server side using the following function: protected void isRecordAlreadyExist(TextBox txt_Value, int res) { ds_main = new Data ...

I currently possess a certain document stored in the database. Is there a way to create a query using mongoose that will allow me to remove an item from the "cart" array within this document?

In this post request, the intention is to remove the item from the "cart" array by identifying it with the product "id". .post('/delete', async (req, res) => { if (await UserProfile.findOneAndDelete({ 'cart.id': req.body.id })) { ...

Modify the innerHTML to adjust font size when a button is clicked in Ionic 5, or eliminate any unnecessary spaces

I have been experimenting with changing the font size of a variable in .html when the variable contains whitespace. In my .ts page, I use the following code to remove the whitespace: this.contents = this.sanitizer.bypassSecurityTrustHtml(this.product[&apos ...

Using forEach Loop with Promise.all in Node.js

I am seeking a solution for a task where I need to read a directory, copy its contents, and create a new file within that same directory. function createFiles(countryCode) { fs.readdir('./app/data', (err, directories) => { if (err) { ...

The slice() function is displaying the correct output in the console, but the string is not being updated in the <td>

I am facing an issue where the console displays the expected substring, but the original string in the HTML remains unchanged. The goal is to truncate any long text within each table <td>. It's important to note that I'm specifically avoi ...

What methods do publications use to manage HTML5 banner advertisements?

We are working on creating animated ads with 4 distinct frames for online magazines. The magazines have strict size limits - one is 40k and the other is 50k. However, when I made an animated GIF in Photoshop under the size limit, the image quality suffered ...

Using the MongoDB aggregate framework to determine the total employee count per unique state

I'm currently working on displaying the total number of employees for each state within companies located in the USA. I aim to showcase this information for all states included in the dataset using sample numbers as a reference: AZ : 1234 CA : 30000 ...

What is the best way to design a timetable schema in MongoDB specifically for a Teacher Schema?

Greetings to all in the StackOverflow community! I am here seeking some innovative ideas for a project I am currently working on. One of the challenges I'm facing involves storing available days within a Teacher Schema. In this application, a Teacher ...

Adding a class to a Vue component using the $refs property

I am facing an issue where I need to add dynamic class names to various Vue components based on their reference names listed in a configuration file. Manually adding classes to each component is not feasible due to the large number of components. To addre ...

Is it possible to use a variable for the value attribute in a select option?

In a mongodb database, I have a collection that stores "username" and "email". Now, I am trying to create a webpage on a localhost server where I can display the username and email of a specific user based on a selection from a drop down menu. I have succe ...

The message "Error: Unknown custom element: <router-view> - have you properly registered the component?" is prompting for a solution

Even though the name is correctly capitalized in all my component instances, I am still encountering an error. After researching similar issues online, it appears that the problem usually revolves around naming discrepancies. However, I have double-checked ...

Easy method for importing videos into NextJs

Import Coding Guidelines Encountering an error after importing the code, unable to find any solutions online ...

Is it possible for jQuery AJAX to function correctly on mobile Safari, but encounter issues when used on a

I'm encountering an issue with a basic jQuery ajax function that logs the user in through a UIWebView. Strangely, it returns blank only when used in a UIWebView, as it works perfectly in mobile Safari, Chrome, and Firefox on my computer. Below is the ...

Searching Firestore arrays for objects based on one of two fields

Within my document, I am working with the following array: https://i.sstatic.net/j9hBT.png I have a SizeFilterComponent that emits a BaseFilter object when a size is selected. Multiple sizes can be selected. Here is the method handling this logic: selecti ...

Retrieve the part of a displayed element

Presently, I am developing a modal system using React. A button is located in the sidebar and the modal is represented as a div within the body. In the render function of the main component of my application, two components are being rendered: MyModal M ...

Implementing automatic line breaks in Bootstrap

When setting the "overflow scroll able" option, I want it to only allow scrolling in the y direction and if x content overflows, a line break should occur. I tried applying 'white-space', but it didn't work as expected. <ul class="s ...

Update the JSON data following deletion

I have received the following JSON data: "memberValidations": [ { "field": "PRIMARY_EMAIL", "errorCode": "com.endeavour.data.validation.PRIMARY_EMAIL", "createdDateTime": null }, ...

Is there a more efficient way to handle multiple arrays using a combination of .post() and PHP scripts, or can it all be processed in

I'm currently using a .post() request to fetch a PHP array into JavaScript. Here's an example: $.post("example.php",{"data":user},function( result ){ alert(result);},'json'); It works perfectly fine with a single array; however, I now ...

State of loading getServerSideProps in Next.js

Can we implement a loading state similar to when retrieving data on the client-side? I'm interested in having a loading state, maybe with a loading-skeleton like react-loading-skeleton On the client-side, we can achieve this by: import useSWR from & ...

Ways to refresh a webxr session while clearing all models from the scene

Whenever the webxr session restarts, I notice that two instances of previous objects appear on the screen. I want the screen to be clear when the session restarts. Currently, I am using the following code: for( var i = scene.children.length - 1; i >= 0 ...