3

这将是一个相当复杂的问题,所以我会继续添加它。

我的应用程序由两种主要类型的视图构成 - 标准视图和区域(一种特殊类型的视图,专门用于包含其他视图。我的根应用程序视图是一个区域,由各种其他区域组成,然后我可以“插入” ' 视需要而定。

我位于主要应用程序区域(页眉、页脚、模式等)的所有视图都可以正常工作。今天我尝试在其他视图中创建一些子区域,但遇到了障碍。出于某种原因,当我调用this.$el.html()该区域以传递该区域的分配视图的输出时,什么也没有发生。我可以单步执行代码,并且视图在自身内部呈现得很好,并且我可以通过查看控制台中的对象模型来查看标记。然而,它实际上从未连接到页面,我所看到的只是代表区域包装器的标记。

这是一些代码 - 希望它会有意义,但这会下降很多级别......

首先,我的视图和区域的基类...

define(['backbone', 'helpers/cookie-manager'],
    function (Backbone, CookieManager) {

        var spinner = "<img src='/content/images/global/ajax-loader.png' alt='loading...' />";        

        var ministryView = Backbone.View.extend({

            name: 'Unnamed View',
            sectionName: 'No section specified',

            stateRequired: false,

            template: undefined,

            bindings: [],

            initialize: function (options) {
                this.options = options || {};
                Backbone.View.prototype.initialize.call(this, options);
                if (this.options.name) {
                    this.name = this.options.name;
                }
                if (this.options.sectionName) {
                    this.sectionName = this.options.sectionName;
                }
                if (this.options.template) {
                    this.template = this.options.template;
                }
            },

            bindToModel: function (model, ev, callback, that) {
                if (that === undefined || that === null) {
                    throw "The value of 'that' needs the context of the extending class in order to operate correctly.";
                }
                model.bind(ev, callback, that);
                this.bindings.push({ model: model, ev: ev, callback: callback });
            },

            dispose: function () {
                this.unbindFromAllModels();   // Will unbind all events this view has bound to
                this.stopListening();
                this.unbind();                // This will unbind all listeners to events from this view. This is probably not necessary because this view will be garbage collected.
                this.remove();                // Uses the default Backbone.View.remove() method which removes this.el from the DOM and removes DOM events.
                this.undelegateEvents();
            },

            render: function () {
                this.trigger('rendered');
                return this;
            },

            resetStyleState: function(condition) {
            },

            trash: function () {
                this.dispose();
            },

            unbindFromAllModels: function () {
                _.each(this.bindings, function (binding) {
                    binding.model.unbind(binding.ev, binding.callback);
                });
                this.bindings = [];
            }
        });

        var ministryRegion = ministryView.extend({

            name: 'Unnamed Region',

            currentView: undefined,

            initialize: function (options) {
                this.options = options || {};
                ministryView.prototype.initialize.call(this, options);
                if (this.options.currentView) {
                    this.currentView = this.options.currentView;
                }
                _.bindAll(this, 'placeRenderedView');
                _.bindAll(this, 'showRendering');
            },

            placeRenderedView: function () {
                this.$el.html(this.currentView.$el);
                this.currentView.delegateEvents();

                if (this.currentView.postRender !== undefined && this.currentView.postRender !== null) {
                    this.currentView.postRender();
                }
            },

            renderView: function (view) {
                if (view) {
                    if (this.currentView) {
                        this.currentView.trash();
                    }

                    this.currentView = view;
                }

                this.currentView.bind('rendering', this.showRendering);
                this.currentView.bind('rendered', this.placeRenderedView);
                this.currentView.render();
            },

            showRendering: function () {
                this.$el.html(spinner);
            },

            trash: function(disposeRegion) {
                this.currentView.trash();

                if (disposeRegion !== undefined && disposeRegion !== null && disposeRegion !== false) {
                    this.dispose();
                }
            }
        });


        return {
            View: ministryView,
            Region: ministryRegion
        };
    });

现在加载到应用程序中的视图包含我想要将视图加载到 ( mealPlansRegion) 中的区域...

define(['ministry', 'jquery', 'views/v-header', 'models/m-ns', 'views/components/components', 'text!templates/hub/member-home.html'],
    function (Ministry, $, Header, Models, Components, TemplateSource) {    
        var memberHomeView = Ministry.SecureView.extend({

            name: 'Member Home',
            sectionName: 'Hub',

            mealPlansRegion: undefined,

            template: Handlebars.compile(TemplateSource),

            headerView: new Header({ text: 'Kitchen Hub', swatch: 'a' }),

            initialize: function (options) {
                Ministry.SecureView.prototype.initialize.call(this, options);
            },

            // Need to override the normal secured view implementation.
            render: function () {
                this.$el.html(this.template(this));
                this.mealPlansRegion = new Ministry.Region({ el: '.meal-plans-container' });
                this.mealPlansRegion.renderView(new Components.MealPlansList({ collection: new Models.MealPlan.OwnedCollection({ username: App.session.username() }) }));
                this.trigger('rendered');
                return this;
            },

            postRender: function () {
                if (!this.isSecured()) {
                    App.router.navigate('/');
                    App.renderHome(false);
                }
            }
        });

        return memberHomeView;
    });

...它是模板...

<section class="meal-plans-container">
</section>

...目前仅包含该地区的占位符。最终,目的是让其中的几个具有可互换的内容。最后,这是我要加载的视图...

define(['ministry', 'jquery', 'models/m-meal-plan', 'text!templates/components/meal-plans-list.html'],
    function(Ministry, $, MealPlan, TemplateSource) {
        var mealPlansListView = Ministry.SecureView.extend({

            name: 'Meal Plans List Component',

            template: Handlebars.compile(TemplateSource),

            render: function () {
                var that = this;

                if (this.isSecured()) {
                    this.collection.on('fetching', function () {
                        that.trigger('rendering');
                    });

                    this.collection.fetch({
                        success: function() {
                            that.bindData();
                            that.trigger('rendered');
                        },
                        error: function(model, xhr) {
                            that.$el.html('Unable to fetch meal plan data');
                            if (console !== undefined && console !== null) {
                                console.log('Fetch Meal Plan failed: ' + xhr.responseText);
                            }
                            that.trigger('rendered');
                        }
                    });
                } else {
                    this.applySecureLoginPrompt();
                }

                return this;
            },

            bindData: function () {
                this.$el.html(this.template({ plans: this.collection.toJSON() }));
            }
        });

        return mealPlansListView;
    });

它是模板...

<ul id="mealPlansList" class="swatch-listview-b">
    <li class="listview-header">Meal Plans</li>
    {{#each plans}}
    <li><span class="meal-plan-id-holder hidden">{{id}}</span>{{name}}</li>
    {{/each}}
</ul>

对于这个特定的视图,这部分公共区域代码失败了......

        placeRenderedView: function () {
            this.$el.html(this.currentView.$el);
            this.currentView.delegateEvents();

            if (this.currentView.postRender !== undefined && this.currentView.postRender !== null) {
                this.currentView.postRender();
            }
        },

...而且这this.$el.html(this.currentView.$el);条线根本没有做任何事情。

如果我能提供任何其他帮助,请告诉我。

4

1 回答 1

2

在这篇文章的帮助下,我设法解决了这个问题 - Backbone View Nesting

我重写了memberHomeView类并将区域实例化从函数render移到了postRender函数中。这确保了模板渲染已经完成,从而允许该区域正确实例化(现在回到我身边,这就是我postRender首先创建该方法的原因。

这是更改后的功能...

define(['ministry', 'jquery', 'views/v-header', 'models/m-ns', 'views/components/components', 'text!templates/hub/member-home.html'],
    function (Ministry, $, Header, Models, Components, TemplateSource) {    
        var memberHomeView = Ministry.SecureView.extend({

            name: 'Member Home',
            sectionName: 'Hub',

            mealPlansRegion: undefined,

            template: Handlebars.compile(TemplateSource),

            headerView: new Header({ text: 'Kitchen Hub', swatch: 'a' }),

            initialize: function (options) {
                Ministry.SecureView.prototype.initialize.call(this, options);
            },

            // Need to override the normal secured view implementation.
            render: function () {
                this.$el.html(this.template(this));
                this.trigger('rendered');
                return this;
            },

            postRender: function () {
                if (!this.isSecured()) {
                    SiansPlanApp.router.navigate('/');
                    SiansPlanApp.renderHome(false);
                } else {
                    // MOVED THE REGION INSTANTIATION HERE
                    this.mealPlansRegion = new Ministry.Region({ el: '.meal-plans-container' });
                    this.mealPlansRegion.renderView(new Components.MealPlansList({ collection: new Models.MealPlan.OwnedCollection({ username: SiansPlanApp.session.username() }) }));
                }
            }
        });

        return memberHomeView;
    });

简单来说....


如果附加到外部标记,请确保标记已呈现,然后再尝试添加使用它的子视图或区域,否则您可能会哭。


于 2013-08-27T21:33:37.320 回答