How can one properly refresh the model for a static route in Ember.js?

I have a basic array of models that are displayed in a list (path: /things) and are loaded from a REST-API.

In a nested route (/things/add), there is functionality to add a new model, which is then saved via the REST-API.

After adding the new model, a transitionTo('things') method is used to return to the list.

According to the Ember documentation, when using "transitionTo" on non-dynamic routes, neither the model hook nor the setupController-Hook are called.

What is the best approach to refresh the model on a non-dynamic route using transitionTo? Or what is the optimal way to reload a model on a non-dynamic route without using transitionTo?

app.js

// App Initialization
App = Ember.Application.create();

// Routes
App.Router.map(function() {
    this.resource('things', function() {
        this.route('add');
    })
});

App.IndexRoute = Ember.Route.extend({
    redirect : function() {
        this.transitionTo('things');
    }
});

App.ThingsRoute = Ember.Route.extend({
    model : function(param) {
        return App.Thing.findAll();
    },
});

App.ThingsAddRoute = Em.Route.extend({
    setupController : function(controller) {
        controller.set('content', App.Thing.create());
    }
});

// Models
App.Thing = Ember.Object.extend({
    name : null,
    description : null
});

App.Thing.reopenClass({
    findAll : function() {
        var result;
        $.ajax({
            url : 'http://path/app_dev.php/api/things',
            dataType : 'json',
            async : false,
            success : function(data) {
                result = data.things;
            }
        });
        return result;
    },
    save : function(content) {
        console.log(content);
        $.ajax({
            type : 'post',
            url : 'http://path/app_dev.php/api/things',
            data : {
                name : content.name,
                description : content.description
            },
            async : false
        });
    }
});

// Controller
App.ThingsAddController = Em.ObjectController.extend({
    add : function() {
        App.Thing.save(this.content);
        this.transitionToRoute('things');
    },
    cancelAdding : function() {
        this.transitionToRoute('things');
    }
});

index.html

<script type="text/x-handlebars">
<div class="container">
    <div class="row">
        <div class="span12">
            <h1>List of things</h1>
        </div>
        {{outlet}}
    </div>
</div>
</script>

<script type="text/x-handlebars" data-template-name="things/add">
<div class="span12">
        <form class="form-horizontal">
        <fieldset>
            <div id="legend">
                <legend class="">Add new thing</legend>
            </div>

            <!-- Name -->
            <div class="control-group">
                <label class="control-label" for="name">Name</label>
                <div class="controls">
                    {{view Ember.TextField id="name" placeholder="Enter Name" valueBinding="name"}}
                </div>
            </div>

            <!-- Description -->
            <div class="control-group">
                <label class="control-label" for="description">Description</label>
                <div class="controls">
                    {{view Ember.TextArea id="description" placeholder="Enter description" valueBinding="description"}}
                </div>
            </div>

            <!-- Submit -->
            <div class="control-group">
                <div class="controls">
                    <button class="btn btn-success" {{action add}}>Save</button>
                    <button class="btn" {{action cancelAdding}}>Cancel</button>
                </div>
            </div>

        </fieldset>
        </form>
</div>
</script>    

<script type="text/x-handlebars" data-template-name="things">
<div class="span12">
    <div class="btn-toolbar">
        <div class="btn-group">
            {{#linkTo things.add}}<i class="icon-plus"></i> add new thing{{/linkTo}}
        </div>
    </div>
</div>
{{outlet}}  
<div class="span12">
    <table cellpadding="0" cellspacing="0" border="0" class="table table-striped ">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Description</th>
            </tr>
        </thead>
        <tbody>
        {{#each item in model}}
            <tr>
                <td>{{item.id}}</td>
                <td>{{item.name}}</td>
                <td>{{item.description}}</td>
            </tr>
        {{/each}}
        </tbody>
    </table>
</div>
</script>

Answer №1

When working with ember-data, saving a record will automatically update the results of findAll(). This can be achieved by either manually updating the array or triggering a refresh when a new record is added. It is recommended to do this from the add function in ThingsAddController. Here's an example:

App.ThingsAddController = Em.ObjectController.extend({
  needs: [things],
  add : function() {
    newThing = App.Thing.save(this.content);
    this.get('controllers.things').pushObject(newThing);
    this.transitionToRoute('things');
  },
});

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

"Having trouble with the Ng-click function not functioning properly

I am facing an issue with my controller code. I have set up an http request and upon completion, I trigger another view using ng-click. However, for some reason, my ng-click functionality is not working as expected. Below is the snippet of my code: app.c ...

Implementing Async Detect Series for Output Retrieval in Node.js

I'm looking to implement a process where I can return output based on asynchronous calls while iterating through an array. The goal is to stop the iteration once a desired response is obtained from a Third Party Server and return that response. To ac ...

Online portal for showcasing merchandise

I am currently working on developing a compact web store using .net. This web store solution will house multiple "webshops" all utilizing the same server. My main concern is regarding performance issues when it comes to using jQuery Ajax calls to retrieve ...

Is there a way to trigger the onclick event while dragging the div?

Exploring a Div: <div id="up" onmousedown="handleMouseDown('url(/scanToUserBox/img/cpt_subfunc_005_prev_p.png)', this)" onclick="changePage('up')"> </div> Upon clicking the div, the onmousedown event is trig ...

Dropbox menu within an extended webpage

I am looking to create a dropdown menu that behaves like the one on this website. The goal is for the dropdown to cover the entire webpage, hide the scroll bar, and "unmount" the other elements of the page, while still displaying them during the transition ...

How can multiple arguments be passed to a function using JQuery's post method?

I can't seem to figure out how to pass multiple arguments to a function using jQuery's post method. It might sound like a silly question, but I'm struggling with it. Currently, my code looks something like this: $.post("<?php echo site_ ...

Image remains fluid within a static div without resizing

Any assistance would be greatly appreciated. I am currently facing an issue with a fixed div that is floating at the bottom of the screen, serving as ad space for the mobile version of a website. The problem arises when attempting to resize the browser win ...

What could be causing a syntax error when I use `npm run start` with npm react-scripts?

After months of working on a full stack React app, I encountered an unexpected error when trying to run npm run start from the command line. The error message was as follows: // npm run start > [email protected] start /Users/eden/Documents/GitH ...

Tips for creating a responsive background image that adjusts after resizing the window to a certain width

Is there a way to create a responsive background-image that adjusts when the window is resized to a specific width, similar to the main image on ? ...

Having trouble showing Firebase data on a basic Vue application

I've been working on a simple Vue+Firebase application that allows users to send strings to the Firebase database and have the messages displayed using the "v-for" directive. However, I keep encountering an error message stating: Property or method " ...

The onSubmit function fails to run when triggered from a component nested within another component

In my next.js project, I have a component that utilizes the NavbarItem component. The NavbarItem component uses Login to display a login form. This NavbarItem component takes the Login component as a parameter for its function. However, in this configura ...

Run JavaScript code last before page unloads

Two pages are involved in this process. On the first page, there is a form that the user completes and then clicks on the submit button. After that, the code for the first page unloads, and the user is redirected to the second page. Actual Issue A loadin ...

The state has been modified, but the component is failing to trigger a re-render

Utilizing the MUI card component to show all the posts of a logged-in user. This MUI card has the capability to expand or collapse based on the values of true or false. Each card is assigned a key called expanded, which is initially set as an empty string. ...

Guide to implementing tooltips for disabled <li> elements in AngularJS

I have a list of items that are displayed using the following code: <li class="dropdown-item" data-toggle="tooltip" uib-tooltip="tooltip goes here" data-placement="left" data-ng-repeat="result in items.results.contextValues.rows " ...

react-helmet isn't detecting all the dynamic meta properties

Utilizing React to generate preview images for various platforms like WhatsApp and Facebook has been my current focus. My goal is to have the preview image correspond to a specific product when a distinct URL is provided. Currently, I have managed to disp ...

Angular-dc bar graph failing to display properly

I'm having some trouble creating a bar chart using crossfilter, dc.js, and angular-dc. The rowchart is working properly, but the barchart is not displaying the bars. When I inspect the element in Chrome, I can see the values, and when I force focus, t ...

Is there a way for multiple <select> elements to have identical options in React?

Currently, I have a React component structured like this: export default function ExampleComponent() { return ( <div> <select required name="select1"> <option label=" "></opti ...

Ways to troubleshoot a validation error when the user selects the captcha

I have incorporated a captcha into my asp.net MVC core web application using the following code: <div class="form-group"> <div class="col-md-2"></div> <div class=" ...

Leveraging AngularJS to enhance the dynamic HTML content within Datatables

My angular application includes a Datatable where I alter cell content to include HTML elements. In the given code snippet, I specifically modify the cell content of the 5th column to incorporate links. Additionally, I intend to implement a tooltip featur ...

dismiss facial recognition event

Does anyone know how to implement a cancel button in Facebox when using it to delete data from MySQL? I want the window to unload when the user clicks on cancel. This is the code snippet I am currently using with Facebox: Are You Sure You Want To Delete ...