视图中视图中的骨干视图 - 为什么这样。$ el.html('在这里插入一些内容')什么都不做?

时间:2013-08-27 21:14:01

标签: javascript backbone.js

这将是一个非常复杂的问题,因此我会继续添加它。

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

我在主应用程序区域(页眉,页脚,模态等)中的所有视图都可以正常工作。今天我尝试在其他视图中创建一些子区域,但我遇到了障碍。出于某种原因,当我在区域上调用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);行根本不做任何事情。

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

1 个答案:

答案 0 :(得分: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;
    });

简单来说......


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