Вычисляемое свойство в контроллере на основе модели маршрута в EmberJS

Я хочу реализовать вычисляемое свойство в контроллере, которое изменяется при изменении данных в модели маршрута.

Маршрут:

import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        return new Ember.RSVP.hash({
            ingredients: this.store.findAll('ingredient'),
            recipes: this.store.peekAll('recipe')
        });
    },

    setupController: function(controller, modelHash) {
        controller.setProperties(modelHash);
    }
});

контроллер:

import Ember from 'ember';

export default Ember.Controller.extend({
    pageNumber: 0,
    pageSize: 16,

    pages: function() {
        var pages = [];
        if (this.model != null) {
            var content = this.model.recipes;
            while (content.length > 0) {
                pages.push(content.splice(0, this.get("pageSize")));
            }
        }
        return pages;
    }.property('model.recipes.@each', 'pageSize'), 

    recipesOnPage: function() {
        return this.get('pages')[this.get('pageNumber')];
    }.property('pages', 'pageNumber')
});

Этот код не выдает ошибки, но не работает - "страницы" всегда пусты. И свойство "pages" не пересчитывается при смене модели. Что я делаю неправильно? И как добиться желаемого результата?

PS Ember версия - 1.13.

2 ответа

Решение

Так как вы изменили setupController крюк, твой controller имеет свойства ingredients а также recipes, но не имеет model имущество.

Итак, ваше вычисленное свойство должно быть:

pages: function() {
 // avoid using model here
 // use this.get('recipes') instead of this.model.recipes
}.property('recipes.[]', 'pageSize')

Ссылка направляющих крючка SetupController.

Пожалуйста, попробуй:

import Ember from 'ember';

export default Ember.Controller.extend({
    pageNumber: 0,
    pageSize: 16,

    pages: function() {
        var pages = [];
        var model = this.get('model');
        if (model != null) {
            var content = model.get('recipes');
            while (content.length > 0) {
                pages.push(content.splice(0, this.get("pageSize")));
            }
        }
        return pages;
    }.property('model.recipes.@each', 'pageSize'), 

    recipesOnPage: function() {
        return this.get('pages')[this.get('pageNumber')];
    }.property('pages', 'pageNumber')
});
Другие вопросы по тегам