Pub - Sub

by bizamajig

HTML

<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
<script src="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css">
<script id="template" type="text/x-jquery-tmpl">
    <div id="macontent" data-role="content">
        <h2>${TITLE}</h2>
        <ul role="listbox" data-role="listview" data-inset="true" >
            <li>${FIRST_ROW}</li>
            <li>${SECOND_ROW}</li>
        </ul>
    </div>
</script>

<div data-role="page" id="page1">
    <div data-role="header">  
        <a id="replace">replace content</a>  
        <a id="replace_without_call">replace without page() call</a>  
        <h3>Static Header</h3>
    </div>
    <div id="existingContent" data-role="content">
        <h2>Static Content</h2>
        <ul role="listbox" data-role="listview" data-inset="true" >
            <li>alpha</li>
            <li>bravo</li>
        </ul>
        <hr/>
        <p>
            This demonstrates the need to call page() on all elements that you've dynamically added to the DOM of a JQM app, so that JQM can style them correctly.</p>
        <p>Note that we are calling page() on *every* element inside the page element.
        </p>
    </div>
</div>

JavaScript

$(document).bind("mobileinit", function() {
    function updateContentWith(viewModel, makePageCall) {
        var template = $('#template'),
            renderedContent = template.tmpl(viewModel);
        $('#page1 div[data-role="content"]').remove();
        $("#page1").append(renderedContent);

        // this is the key - you need call page() on a lot of the content that you've
        // dynamically added to the DOM, so that it can style itself correctly. Note that
        // we are calling page() on *every* element inside the page element.
        if (makePageCall) 
            $("#page1 *").page();
    }

    $("#replace").live('click', function() {
        updateContentWith({
            TITLE: 'Dynamic Content added with page() called after',
            FIRST_ROW: 'row one',
            SECOND_ROW: 'row two'
        },true);
    });
    $("#replace_without_call").live('click', function() {
        updateContentWith({
            TITLE: 'Dynamic Content added without calling page() after',
            FIRST_ROW: 'row one',
            SECOND_ROW: 'row two',
        },false);
    });
}());