I’m creating a mobile view that uses backkbone.js and jquery mobile.
I have a collection that I render to the page, styled up to use jquery mobile’s listview. The collection loads and is rendered on the page with the correct html, but renders as an un-styled list, not how it should render in jquery mobile. If I then inspect the list, copy it as html, and paste it into my html page as static html, that html displays correctly!
What am I doing wrong? This is my first foray into both backbone.js and jquery mobile so it could be something simple.
Code:
My templates:
<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>
My views:
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;
}
});
Example HTML output:
<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>
This is how I load the page:
$(document).bind('pageinit',function () {
window.changes = new Changes();
var view = new ChangesView({ collection: changes, el:"#changes" });
changes.fetch();
});
Ok, so by looking around, I found that adding this solved the issue:
But this feels wrong – why should I need to trigger that event myself?