Backbone.js - 使用 jquery 移动渲染渲染渲染的渲染集合,无需样式

Backbone.js - rendering collection with jquery mobile renders without styling

本文关键字:集合 样式 js 使用 jquery 移动 Backbone      更新时间:2023-09-26

我正在创建一个使用backkbone.js和jquery mobile的移动视图。

我有一个呈现到页面的集合,样式设置为使用 jquery mobile 的列表视图。该集合加载并使用正确的 html 呈现在页面上,但呈现为非样式列表,而不是它在 jquery mobile 中呈现的方式。如果我然后检查列表,将其复制为 html,然后将其作为静态 html 粘贴到我的 html 页面中,则该 html 会正确显示!

我做错了什么?这是我第一次涉足 Backbone.js 和 jquery mobile,所以它可能很简单。

法典:

我的模板:

<script id="change-template" type="text/template">
<a href="#">{{ Description }}</a>
<p>{{ ChannelLabel }}</p>
</script>
<script id="changes-template" type="text/template">
<ul id="changes-list" data-role="listview" data-inset="false" data-filter="true"></ul>
</script>

我的观点:

window.ChangeView = Backbone.View.extend({
    tagName: 'li',
    initialize: function() {
        _.bindAll(this, 'render');
        this.template = _.template($('#change-template').html());
    },
    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
})
window.ChangesView = Backbone.View.extend({
    tagName : "div",
    initialize: function () {
        _.bindAll(this, 'render');
        this.template = _.template($('#changes-template').html());
        this.collection.bind("reset", this.render);
    },
    render: function () {
        var collection = this.collection;
        // Render the template
        $(this.el).html(this.template({}));
        // Then get a handle to the element inside the template.
        var $changes = this.$('#changes-list');
        this.collection.each(function(change) {
            var view = new ChangeView({model: change, collection: collection});
            $changes.append(view.render().el);
        })
        return this;
    }
});

示例 HTML 输出:

<div id="changes" data-role="content" class="ui-content" role="main">
<ul id="changes-list" data-role="listview" data-inset="false" data-filter="true"><li>
  <a href="#">Link Up</a>
  <p>GF1A-R2P24 - 23</p>
  </li><li>
  <a href="#">Link Down</a>
  <p>GF1A-R2P24 - 23</p>
  </li></ul>
</div>

这是我加载页面的方式:

$(document).bind('pageinit',function () {
    window.changes = new Changes();
    var view = new ChangesView({ collection: changes, el:"#changes" });
    changes.fetch();
});
好的

,所以通过环顾四周,我发现添加它解决了这个问题:

$(this.el).trigger( "pagecreate" );

但这感觉不对 - 为什么我需要自己触发该事件?

如果在jQuery Mobile开始设置页面样式之前完成了所有DOM更改,那么它将正常工作。但是,Backbone.js' 事件会导致页面的某些部分异步重新呈现,从而使页面的某些部分没有样式。

调用 .trigger("pagecreate") 或 "create" 会触发 jQuery Mobile 来重新设置页面/元素的样式。

(每次jQuery Mobile显示页面时,它都会读取数据属性并应用适当的样式。

这是必要的,因为jQuery Mobile和Backbone.js是独立的框架。