Danny
Danny

Reputation: 1003

Backbone & Jquery Mobile rendering styles not working - Written in CoffeeScript

I'm using backbone jquery mobile and coffee script to develop a simple twitter application. My problem is the jquery mobile styles are failing to render. My View is

class HomeView extends Backbone.View
constructor: ->
    super

initialize: ->
    @Twitter= new TwitterCollection

template: _.template($('#home').html())

render: ->
    @loadResults()

loadResults: ->
    @Twitter.fetch({
        success: (data) =>
            $(@.el).html(@template({data: data.models, _:_}))

        error: ->
            alert('Error!')
    })

This works fine in terms of pulling information from Twitter, however when

$(@.el).html(@template({data: data.models, _:_}))

is within the fetch function, jquerys styles do not render. Can anyone show me how to refresh the styles? Help would be much appreciated!

For reference, the html template is:

<script type="text/template" id="home">

<div data-role="header" data-position="fixed">
    <h1>TWITTER DATA</h1>
</div>

<div data-role="content">
    <ul data-role="listview"  data-inset="true">
        <% _.each(data, function (row) { %>
            <li><a href="#tweet-<%= row.get('id') %>"><%= row.get('text') %></a></li>
        <% }); %>
    </ul>

    </ul>
</div>

Upvotes: 1

Views: 1142

Answers (2)

madasha
madasha

Reputation: 61

When the fix is applied afterwards (after the view page has been rendered and displayed by $.mobile.changePage()) the user gets an unpleasant side-effect: the view flickers due to the change of style applied by jquery mobile.

My solution to the problem was to trigger custom event from the view once the dynamic rendering is complete and bind the $.mobile.changePage() to that event. This causes the output to be "buffered" until complete and then styled altogether.

Here's an example:

In the initialize function of my view I have code waiting for an event to be fired by the model/collection when fetched and a function to render the dynamic part of the html:

window.MyView = Backbone.View.extend({

// some other code here

initialize: function() {
    this.listenTo(this.collection, "fetchCompleted:CollectionName",  this.renderRows);
},

renderRows: function (eventName) {
    $(this.el).find('div[class="content-primary"]').html(this.template_ul({data: this.collection}));
    this.trigger( 'view:ready' );
},
//...

... then in the router I have the following code for the changePage():

myViewObject.on( 'view:ready', function() {
    $.mobile.changePage($(next.el), {changeHash:false, transition: transition});
});

Upvotes: 0

Danny
Danny

Reputation: 1003

Ok, I fixed it by adding ".listview('refresh').trigger('create');" to the end of

$(@.el).html(@template({data: data.models, _:_}))

Upvotes: 1

Related Questions