Route only loads page updates - Ember JS

I am currently learning Ember and I am making a simple application, but I am having a weird problem. I have a route setup and it only retrieves data when I reload the page. Here is my code:

// Start Ember application
App = Ember.Application.create({
    LOG_TRANSITIONS: true
});

// Router paths
App.Router.map(function () {

    // Homepage
    this.resource('index', { path: '/' });

    // Book view
    this.resource('book', { path: '/book/:id/:version' });

});

// Homepage route
App.IndexRoute = Ember.Route.extend({
    model: function () {
        // Get all the books
        return Ember.$.getJSON('/books');
    }
});


// Single book view
App.BookRoute = Ember.Route.extend({
    model: function (params) {
        // Get a single book
        return Ember.$.getJSON('/book?id=' + params.id + '&version=' + params.version);
    }
});

When I go to / # / book / 1/1 by clicking on the main page, the page is empty. When I just refresh the page, when I'm there, it loads the data, and everything works.

Why is this? What can I do to make it work when the user clicks on the main page?

+4
source share
4 answers

Thank you all for your suggestions. I figured it out with this code here:

App.BookRoute = Ember.Route.extend({
    setupController: function (controller,model) {
        // Get a single book
        Ember.$.getJSON('/book?id=' + model.id + '&version=' + model.version,
            function (data) {
                controller.set('model',data);
            });
    }
});

I used setupController instead of model.

+1
source

link-to helper, ... id,

{{#each book in books}}
  {{#link-to "book" book.id}}{{book.name}}{{/link-to}}
{{/each}}

.

0

Ember link-to model. , :

// In the index template
{{#each book in model}}
  {{#link-to 'book' book}}{{book.name}}{{/link-to}}
{{/each}}

, , , BookRoute . BookController#init . , .

App.BookController = Ember.Controller.extend({
  init: function() {
    this._super();

    // Replace doesNotHaveAllInfo with your check
    if (doesNotHaveAllInfo) {
      this.set('model', Ember.$.getJSON('/book?id=' + this.get('model.id') + '&version=' +  this.get('model.version')));
    }
  },
});

, link-to, . , , , index, id version.

, , model, doesNotHaveAllInfo false. link-to , .

I would also recommend abstracting the code Ember.$.getJSONinto a reusable method, perhaps on a model, for example:

App.Book.reopenClass({
  find: function(id, version) {
    return Ember.$.getJSON('/book?id=' + id + '&version=' +  version);
  }
});

Then you can use App.Book.find()to return your model both on your route and on yours BookController.

-1
source

All Articles