дочерние коллекции не отображаются в представлении родительской модели в магистрали

Кажется, я не могу заставить шаблоны просмотра детей отображать. Они отображаются в журнале консоли, и они появляются нужное количество раз, но я не могу заставить их отображаться в браузере.

Цели — это родители, а шаги — дети.

БИТЫ КОДА:

модели:

$(function() {
    window.Goal = Backbone.Model.extend({
        defaults: {
        description: null
        },
        initialize: function() {
            this.steps = new Steps();
            this.steps.fetch({ reset: true });
            this.stepsAll = new StepsViewForGoals({ collection:this.steps });
            $('.all-steps').append(this.stepsAll.render().el);
        }
    });
    window.Goals = Backbone.Collection.extend({
        model: Goal,
        url: '/api/goals/'
    });
    window.goals = new Goals();
});

просмотры целей:

$(function() {
    window.GoalView = Backbone.View.extend({
        className: 'list-item',
        template: _.template($('#goal-item-template').html()),
        initialize: function() {
            _.bindAll(this, 'render');
            this.model.bind('change', this.render);
        },
        render: function() {
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        }
    });
    window.GoalsView = Backbone.View.extend({
        el: '#app',
        template: _.template($('#goals-list-template').html()),
        initialize: function () {
            _.bindAll(this, 'render', 'addGoal');
            this.collection.bind('reset', this.render);
            this.collection.bind('change', this.render);
            this.collection.bind('add', this.render);
        },
        render: function() {
            this.$el.html(this.template());
            this.collection.each(function(goal) {
                var view = new GoalView({ model:goal });
                $('#goals').append(view.render().el);
            });
            return this;
        }
    });
});

пошаговые просмотры

$(function() {
    window.StepView = Backbone.View.extend({
        className: 'list-item',
        template: _.template($('#step-item-template').html()),
        initialize: function () {
            _.bindAll(this, 'render');
            this.model.bind('change', this.render);
        },
        render: function() {
            this.$el.html(this.template(this.model.toJSON()));
            console.log('Individual step');
            return this;
        }
    });
    window.StepsViewForGoals = Backbone.View.extend({
        el: '.all-steps',
        template: _.template($('#step-list-template').html()),
        initialize: function () {
            _.bindAll(this, 'render');
            this.collection.bind('reset', this.render);
            this.collection.bind('change', this.render);
        },
        render: function() {
            this.$el.html(this.template());
            console.log(this.collection.toJSON());
            this.collection.each(function(step) {
                var view = new StepView({ model:step });
                $('.all-steps-list').append(view.render().el);
            });
            console.log('Steps View');
            return this;
        }
    });
});

Шаблон родительской модели:

{% verbatim %}

    <script id="goal-item-template" type="text/template">
        <h4><a class="controls-toggle"><%- description %></a></h4>
        <div class="controls">
            <a class="edit">
                <span class="ss-icon ss-pika edit-toggle">edit</span>
                <span class="ss-icon ss-pike save-toggle">save</span>
            </a>
            <a class="remove">
                <span class="ss-icon ss-pika">delete</span>
            </a>
        </div>
        <div class="edit-func">
            <div class="form-block">
                <textarea name="description"><%- description %></textarea>
            </div>
            <div class="all-steps"></div>
        </div>
    </script>

{% endverbatim %}

шаблон списка дочерних элементов

{% verbatim %}

    <script id="step-list-template" type="text/template">
        <h1 class="section-title">My Steps</h1>
        <div id="steps" class="all-steps-list"></div>
    </script>

{% endverbatim %}

Роутер для ясности:

$(function() {
    window.AppRouter = Backbone.Router.extend({
        routes: {
            'goals/': 'goals',
            'steps/': 'steps'
        },
        initialize: function() {
            // Goals
            this.goalsview = new GoalsView({
                collection: goals
            });
            goals.fetch({ reset:true });

            this.stepsview = new StepsView({
                collection: steps
            });
            steps.fetch({ reset:true });
        },
        goals: function () {
            $('#app').empty();
            $('#app').append(this.goalsview.render().el);
        },
        steps: function () {
            $('#app').empty();
            $('#app').append(this.stepsview.render().el);
        }
    });

    window.appRouter = new AppRouter();
    Backbone.history.start();
});

person Dave Merwin    schedule 06.11.2013    source источник
comment
некоторые шаблоны отсутствуют??   -  person thecodejack    schedule 06.11.2013
comment
если возможно, сделайте ссылку jsbin или fiddle и поделитесь здесь.   -  person thecodejack    schedule 06.11.2013
comment
Я создал для него jsbin. См. здесь: jsbin.com/egIyOZe/2   -  person Dave Merwin    schedule 06.11.2013


Ответы (2)


Ваш код выглядит неполным, поэтому просто добавил недостающие части. С помощью следующего кода я мог видеть, как отображаются представления целей и шагов. Дайте мне знать, если ваш код отличается.

$(function () {

    window.Step = Backbone.Model.extend({
    })

    window.Steps = Backbone.Collection.extend({
        model:window.Step,
        url: 'data/steps.json'
    })

    window.Goal = Backbone.Model.extend({
        defaults: {
            description: null
        },
        initialize: function () {
            this.steps = new Steps();
            this.steps.fetch({ reset: true });
            this.stepsAll = new StepsViewForGoals({ collection: this.steps });
            $('.all-steps').append(this.stepsAll.render().el);
        }
    });
    window.Goals = Backbone.Collection.extend({
        model: Goal,
        url: 'data/goals.json'
    });

    window.goals = new Goals();

});


$(function () {
    window.GoalView = Backbone.View.extend({
        className: 'list-item',
        template: _.template($('#goal-item-template').html()),
        initialize: function () {
            _.bindAll(this, 'render');
            this.model.bind('change', this.render);
        },
        render: function () {
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        }
    });
    window.GoalsView = Backbone.View.extend({
        el: '#app',
        template: _.template($('#goals-list-template').html()),
        initialize: function () {
            _.bindAll(this, 'render');
            this.collection.bind('reset', this.render);
            this.collection.bind('change', this.render);
            this.collection.bind('add', this.render);
        },
        render: function () {
            this.$el.html(this.template());
            this.collection.each(function (goal) {
                var view = new GoalView({ model: goal });
                $('#goals').append(view.render().el);
            });
            return this;
        }
    });
});


$(function () {
    window.StepView = Backbone.View.extend({
        className: 'list-item',
        template: _.template($('#step-item-template').html()),
        initialize: function () {
            _.bindAll(this, 'render');
            this.model.bind('change', this.render);
        },
        render: function () {
            this.$el.html(this.template(this.model.toJSON()));
            console.log('Individual step');
            return this;
        }
    });
    window.StepsViewForGoals = Backbone.View.extend({
        el: '.all-steps',
        template: _.template($('#step-list-template').html()),
        initialize: function () {
            _.bindAll(this, 'render');
            this.collection.bind('reset', this.render);
            this.collection.bind('change', this.render);
        },
        render: function () {
            this.$el.html(this.template());
            console.log(this.collection.toJSON());
            this.collection.each(function (step) {
                var view = new StepView({ model: step });
                $('.all-steps-list').append(view.render().el);
            });
            console.log('Steps View');
            return this;
        }
    });
});


$(function () {
    var view = new window.GoalsView({
        collection:window.goals
    });
    view.render();
    window.goals.fetch();
})
person Ravi Hamsa    schedule 06.11.2013
comment
всякий раз, когда что-то не работает, вы должны сначала заглянуть в консоль. - person Ravi Hamsa; 06.11.2013
comment
Я исправил код для рендера. Однако это все еще не отображает представления. Кроме того, я не уверен, что вы имеете в виду под комментарием о консоли. Я использовал консоль, чтобы убедиться, что все загружается. Я не видел ошибки в консоли. Возможно, я не понимаю, что вижу, но неопределенных ошибок или пустых массивов не было. Спасибо за помощь. - person Dave Merwin; 06.11.2013
comment
Я не уверен, что понимаю ваши изменения. Независимо от того, что обрабатывается маршрутизатором. Проблема заключается в том, что шаги не заполняют цели, а не цели не загружаются. Я добавил маршрутизатор, чтобы вы могли видеть, что цели загружаются. Прошу прощения, если я не вижу, что вы пытаетесь указать. - person Dave Merwin; 06.11.2013

Я нашел это.

Проблема в том, ГДЕ делается вызов рендеринга.

Это должно быть сделано в РОДИТЕЛЬСКОЙ точке зрения, где вы видите ребенка. Я делал все это в функции инициализации, но это просто поместило вызов рендеринга в представление, которое все еще находится в памяти. Как только я переместил рендер из model.initialize в parent.view.render, он заработал.

person Dave Merwin    schedule 06.11.2013