【问题标题】:Refactor Me: Backbone.js Sub-View Rendering Optimization重构我:Backbone.js 子视图渲染优化
【发布时间】:2011-08-25 21:54:45
【问题描述】:

我正在使用 Backbone.js v0.5.5 开发一个单页应用程序,在应用程序的一个“页面”上,我有一个主视图 (audioOnDemand) 和两个辅助视图(audioPlay 和 audioNav)。我希望辅助视图是可路由的,例如,用户可以转到“#audio_ondemand”、“#audio_ondemand/id/:id”或“#audio_ondemand/page/:page”,一切都会加载.为了完成这项工作,我最终不得不在我的控制器/路由器中放入一些 jQuery 代码,这感觉非常 hacky。这就是我来这里的原因,看看是否有更好的方法。

这是我的控制器/路由器。

audio_ondemand: function(splat) {
    this._audioondemandview = new AudioOnDemandView();
    this._audioondemandview.render();

    if (splat) {
        var id_patt = /id\/(\d*)/i;
        var id = id_patt.exec(splat);
        id = (id) ? id[1] : null;
        //console.log("id is: "+id);

        var page_patt = /^page\/(\d*)/i;
        var page = page_patt.exec(splat);
    }
    page = (page) ? page[1] : 1;
    //console.log("page is: "+page);

    if (id) {
        setTimeout('app.play_audio("'+id+'");', 500);
    }

    setTimeout('app.audio_nav("'+page+'");', 500);
},

audio_nav: function(page) {
    var nav_holder = $('#pagination-nav');
    if (nav_holder.length == 0) {
        app.audio_ondemand('page/'+page);
    } else {
        var audios = this._audios;
        var nav = new AudioNavView({el: nav_holder, audios: audios, page: page});
        nav.render();
    }
},

play_audio: function(id) {
    var audio_holder = $('#audio-player');
    if (audio_holder.length == 0) {
        app.audio_ondemand('id/'+id);
    } else {
        var audio = this._audios.getByUid(id);
        this._audioview = new AudioView({el: $('#audio-player'), model: audio});
        this._audioview.render();
    }
}

视图没有做任何特别的事情,但这是我的“主”模板(使用 jQuery 模板):

<script id="audioOnDemandTmpl" type="text/x-jquery-tmpl">
    <div class="sub-header">
        <strong>Audio</strong> On Demand
    </div>
    <div id="currently-playing">
        <div id="currently-header">Currently Playing</div>
        <div id="current-holder"></div>
    </div>
    <div id="audio-player"></div>
    <div id="pagination-nav"></div>
    <div id="audios-holder"></div>
</script>

我想你现在已经进退两难了。主视图必须在辅助视图之前渲染,否则辅助视图没有正确的 DOM 元素可以附加到。但是如果我希望辅助视图是可路由的,我必须进行 'hacky' jQuery 检查以查看主视图是否已呈现。

感谢您的任何想法或建议,如果您需要更多详细信息,请告诉我!

更新:因为它可能有助于更好地表达想法,这里是导航视图和模板。

<script id="audioNavTmpl" type="text/x-jquery-tmpl">
    {{if prev > 0}}<a href="#audio_ondemand/page/${prev}">Prev</a> | {{/if}}${current}{{if next}} | <a href="#audio_ondemand/page/${next}">Next</a>{{/if}}
</script>

<script id="audioTmpl" type="text/x-jquery-tmpl">
    <div class="audio-holder">
        <div class="title-author">
            <div class="title"><a href="#audio_ondemand/id/${attributes.uid}">${attributes.title}</a></div>
            <div class="author">${attributes.author}</div>
        </div>
        <div class="topic-date">
            <div class="topic"><strong>${attributes.topic}</strong></div>
            <div class="date">${attributes.date}</div>
        </div>
    </div>
</script>

var AudioNavView = Backbone.View.extend({
audioNavTemplate: $('#audioNavTmpl').template(),
audioTemplate: $('#audioTmpl').template(),

initialize: function(options) {
    this.audios = options.audios.models;

    var temp_page = parseInt(options.page);
    this.page = [
        {
            prev: temp_page - 1,
            current: temp_page,
            next: temp_page + 1
        }
    ];

    this.slice_start = (temp_page - 1) * 11;
    this.slice_end = temp_page * 11;

    this.audios = this.audios.slice(this.slice_start, this.slice_end);

    if (this.audios.length <= 11) {
        this.page[0]["next"] = false;
    }
},

render: function() {
    //console.log(this.page);
    this.el.empty();
    var sg = this;
    $('#audios-holder').fadeOut('fast', function() {
        $.tmpl(sg.audioNavTemplate, sg.page).appendTo(sg.el);
        $(this).empty();
        $.tmpl(sg.audioTemplate, sg.audios).appendTo($(this));
        $(this).fadeIn('fast');
    });
    return this;
}

});

我应该如何更好地设置它,以便如果有人直接从“#home”转到“#audio_ondemand/page/2”,路由器确保在 audioNavView 之前加载 audioOnDemandView?

【问题讨论】:

  • 我不清楚“主”视图和“次要”视图之间的区别。它们似乎都是可路由的视图。在我看来,您的路由器应该跟踪当前呈现的所有视图(路由本身是一个理想的键),并且路由显示或构造并显示视图。
  • 为导航视图添加了更多代码示例,以便更好地了解正在发生的事情。

标签: jquery model-view-controller backbone.js


【解决方案1】:

据我所知,您的嵌套视图只有 1 级深度(即带有子视图的主视图,但没有任何子子视图),因此您可以通过在路由器的初始化方法,然后在路由回调中呈现任何子视图。这是一个非常简单的例子。我用的是underscore的模板引擎,不过思路和jQuery的模板引擎是一样的。

模板:

<script id="master-view" type="text/html">
    Hi, this is a master view. <a href="#subview">Render sub-view now.</a>
    <div id="subview-container"></div>
</script>
<script id="sub-view" type="text/html">
    Hi, this is a sub view.
</script>

主干视图和路由器

var MasterView = Backbone.View.extend({
    _template: _.template($('#master-view').html()),
    render: function () {
        $(this.el).html(this._template());
        return this;
    }
});

var SubView = Backbone.View.extend({
    _template: _.template($('#sub-view').html()),
    render: function () {
        $(this.el).html(this._template());
        return this;
    }
});

var MyRouter = Backbone.Router.extend({

    initialize: function () {
        var view = new MasterView();
        $('body').append(view.render().el);
    },

    routes: {
        '': 'home',
        'subview': 'subview'
    },

    home: function () {
        // probably don't have to do anything
    },

    subview: function () {
        // render subview here
        var view = new SubView({ el: $('#subview-container')[0] });
        view.render();
    }
});

new MyRouter();
Backbone.history.start();

当您将浏览器指向该页面时,您首先只会看到主视图。单击链接,您将看到 url 哈希更改为 #subview 并且将呈现子视图。然后,您可以重新加载页面(url 哈希仍然在#subview),并且子视图将在主视图之后正确呈现。

【讨论】:

    猜你喜欢
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    • 2012-03-09
    • 1970-01-01
    • 2013-06-30
    相关资源
    最近更新 更多