Cereal Killer
Cereal Killer

Reputation: 3414

Re-execute model hook and rerender in Ember js

I have in my Ember App, a route displaying a list of offers; the model is loaded by jquery ajax (I don't use Ember-data):

    Ember.$.ajax({
        type: 'GET',
        url: App.restAPIpath + '/offers/', 
        headers: {
            "tokens": localStorage.tokens
        },
        async: false
    }).then(function(res) {
        data = res.offers;
    });
    return data;

The offers are shown in the template using a datatable and in each row there's a delete button that sends an ajax delete request to the server and correctly deletes the right offer:

{{#view App.dataTableView}}
    <thead>
        <tr>
            <th>Created</th>
            <th>Name</th>
            <th>Deadline</th>
            <th>Duration</th>
            <th>Delete?</th>
        </tr>
    </thead>

    <tfoot>
        <tr>
            <th>Created</th>
            <th>Name</th>
            <th>Deadline</th>
            <th>Duration</th>
            <th>Delete?</th>
        </tr>
    </tfoot>

    <tbody>
        {{#each offer in model}}
            <tr>
                <td>
                    {{offer.createdAt}}
                </td>
                <td>
                    {{#link-to 'eng.offers.edit' offer}}{{offer.name}}{{/link-to}}
                </td>
                <td>
                    {{offer.deadline}}
                </td>
                <td>
                    {{offer.optionDuration}}
                </td>
                <td>
                    <button class="form-button-red" {{action "deleteOffer" offer}}>Delete</button>
                </td>
            </tr>
        {{/each}}
    </tbody>
{{/view}}

but then I need to update the model (and refresh the view?) because if not the deleted offer is still shown until you refresh the page...

Upvotes: 1

Views: 102

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

I'd recommend switching your ajax to async, you'll block the router from doing other important things. You should be able to accomplish the same results doing this:

return Ember.$.ajax({
    type: 'GET',
    url: App.restAPIpath + '/offers/', 
    headers: {
        "tokens": localStorage.tokens
    },
}).then(function(res) {
    return res.offers;
});

Then I'd do something like this for your delete (I'm going to guess a bit of your code) in your controller's delete action:

actions:{
  delete: function(item){
    var self = this;
    Ember.$.ajax({
        type: 'DELETE',
        url: App.restAPIpath + '/delete/' + item.get('id'), 
        headers: {
            "tokens": localStorage.tokens
        },
    }).then(function(){
      //manually remove the item from your collection
      self.removeObject(item);
    });
  }
}

BTW I think delete is a reserved key word and jslint and some minimizers are total haters, so you might do something like deleteItem

Upvotes: 1

Related Questions