Reputation: 45124
I'm using jQuery, jQuery Mobile, Handlebar for this project
I have a courses page as below.
When I click on a course it shows a page as below which contains particular lessons for a course.
Above lessons are taken from a JSON I use Handlebar for this. Below is the Handlebar template.
<script id="lessontemplate" type="text/x-handlebars-template">
{{#each this}}
<li><a href="{{lesson}}">{{lessonname}}</a></li>
{{/each}}
</script>
Below is the JS code which replace the template
("#mycourses").on('click','.mycourse',function(e){
e.preventDefault();
var url = domainURL+'coursedata.php?callback=?';
$.getJSON( url, { courseid: $(this).data('courseid') }, function( data ) {
var tmpl = $('#lessontemplate').html();
console.log(tmpl);
$('h1.coursename').html(data.coursename);
lessontemplate = Handlebars.compile( tmpl );
console.log( lessontemplate(data.coursedetails) );
$('ul#lessons').html( lessontemplate(data.coursedetails) );
$.mobile.changePage("#coursedetails", {transition: 'slide'});
});
});
Then If I go to courses page and click on course, lessons are not shown correctly. It shows the below output.
1st click Console.log() outputs are as below
{{#each this}}
<li><a href="{{lesson}}">{{lessonname}}</a></li>
{{/each}}
<li><a href="1">Lesson Name 1</a></li>
<li><a href="2">Lesson Name 2</a></li>
<li><a href="3">Lesson Name 3</a></li>
2nd click Console.log() outputs are as below
{{#each this}}
<li><a href="{{lesson}}">{{lessonname}}</a></li>
{{/each}}
<li><a href="1">Lesson Name 1</a></li>
<li><a href="2">Lesson Name 2</a></li>
<li><a href="3">Lesson Name 3</a></li>
1st click Console.log() = 2nd click Console.log() but why don't I get the correct output 2nd time? Why does not 2nd time lessons are not shown correctly?
Upvotes: 2
Views: 2313
Reputation: 45124
@Gajotres - Thanks for pointing me to the right direction.
What you have to do is
if ( $('ul#lessons').hasClass('ui-listview'))
{
$('ul#lessons').listview('refresh');
}
else {
$('ul#lessons').trigger('create');
}
Taken from docs.
If you add items to a listview, you'll need to call the refresh() method on it to update the styles and create any nested lists that are added. For example:
$('#mylist').listview('refresh');
Note that the refresh() method only affects new nodes appended to a list. This is done for performance reasons. Any list items already enhanced will be ignored by the refresh process. This means that if you change the contents or attributes on an already enhanced list item, these won't be reflected. If you want a list item to be updated, replace it with fresh markup before calling refresh.
Gajotres answer on some other similar question
Upvotes: 3