Using Handlerbars with Yahoo Pipes - jquery-mobile

I'm trying to pull JSON feeds from a yahoo pipes source into my jQuery Mobile project using Handlebars.js with jQuery's ajax method.
This method works without Handlebars, but there are some limitations. It doesn't show up in jquerymobile listview format, instead it pops out like a normal bullet list. Here's the source:
var pipeURL = "http://pipes.yahoo.com/pipes/pipe.run?_id=mu3NkfY_3BGtncSIJhOy0Q&_render=json";
$.ajax({
url : pipeURL,
dataType : "json",
success : function(data) {
console.log(data);
var html = '<ul data-role="listview" id="all-posts-two" data-filter="" data-count-theme="c">';
$.each(data.value.items, function(i, item) {
html += "<li>" + item.title + "</li>";
});
html += "</ul>";
//Add the feed to the page
$("#PostsList").empty().html(html);
}
});
Here's the source for the other method I've been trying to use with Handlebars but obviously I'm missing something somewhere.
$.ajax({
url : pipeURL,
dataType : "json",
success : function(data) {
//line to check the received data on the console
console.log(data);
//handlebars area
var source = $("#posts-template").html();
var template = Handlebars.compile(source);
var blogData = template(data);
$("#all-posts").append(blogData);
$("#all-posts").trigger("create");
dfd.resolve(data);
},
error : function(data) {
// console.log(data);
}
});
Here's the html source for the template
<ul data-role="listview" id="all-posts" data-filter=""></ul>
<script id="posts-template" type="text/x-handlebars-template">
{{#each value.items}}
<li data-postid="{{ID}}">
<a data-transition="slide" href="#">
<p>{{{title}}}</p>
</a>
</li>
{{/each}}
</script>
Anyone, please help me out please

From what I can see you are using an older version of jQuery Mobile (lower then 1.4).
Do it like this:
var pipeURL = "http://pipes.yahoo.com/pipes/pipe.run?_id=mu3NkfY_3BGtncSIJhOy0Q&_render=json";
$.ajax({
url : pipeURL,
dataType : "json",
success : function(data) {
console.log(data);
var html = '<ul data-role="listview" id="all-posts-two" data-filter="" data-count-theme="c">';
$.each(data.value.items, function(i, item) {
html += "<li>" + item.title + "</li>";
});
html += "</ul>";
//Add the feed to the page
$("#PostsList").empty().html(html);
$('#all-posts-two').listview('refresh');
}
});
Look at this line:
$('#all-posts-two').listview('refresh');
It will enhance dynamically added listview, of course there's one more thing, you need need to trigger it after whole dynamic list has been done and not on every li element, it will fail in this case. In your next example you are using this line:
$("#all-posts").trigger("create");
It will fail because trigger('create') is used to enhance whole data-role="content" not just part of it so as such it should be used only on data-role="content" div.
Read more about it in this other answer.
Or take a look at my blog article, there you will find a working example of listview created from remote JSON data.
Update:
If you are using jQuery Mobile 1.4 try this line:
$('#all-posts-two').enhanceWithin();
.enhanceWithin() is method introduced in jQuery Mobile 1.4 to replace all other methods.
Update 2
This question is finally answered in another question, or you can find it here with working example:

Related

jquery mobile dynamic ul forever formating issue

I know this is an old and boring issue, but i just can´t seem to get it right, i have seen lots of answers telling to refresh, create, enchance etc this is what i have:
my ul in the html file:
<ul id="listaNoticias" data-role="listview" data-split-icon="info" data-split-theme="a" data-inset="true">
my js file:
items='';
$.ajax({
url: '../data/noticias.php',
dataType: 'json',
success: function(data, status)
{
$.each(data, function(index,item)
{
//$('#listaNoticias').append('<li><h2>'+item.titulo+'</h2>'+ '<p>'+item.texto+'</p></li>').listview('refresh');
items += '<li><h2>'+item.titulo+'</h2>'+ '<p>'+item.texto+'</p></li>';
});
$('#listaNoticias').html(items);
$('#listaNoticias').listview('refresh');
},
error: function(){
output.text('There was an error loading the data.');
}
});
If i did a static ul, i would have a listview cell ending like below:
but when adding content dynamically, i have a simple cell like this, which is not what i want:
again i know this is an old issue, but i just can´t seem to figure it out
You forgot to add the second anchor tag in the dynamic listitems:
$.each(data, function(index,item)
{
items += '<li><h2>'+item.titulo+'</h2>'+ '<p>'+item.texto+'</p><a href="#"</a></li>';
});
DEMO

Jquery data-role collapsible events aren't being captured in Jquery Mobile

Could anybody please let me know why the following code isn't working when i am using with Jquery mobile JS
http://jsfiddle.net/znz17ctm/7/
This is my code
<div role="main" class="ui-content oms-content" id="dd">
<div class="myactivelabelsWrap" id="result"></div>
</div>
var response = {
"Restaurants": [{
"RestrntArea": "Haii",
"cust_loc_id": "374"
}, {
"RestrntArea": "rerrrwe",
"cust_loc_id": "373"
}]
}
showLabels();
function showLabels() {
//$("#result").html("");
var favoriteresultag = '';
for (var i = 0; i < response.Restaurants.length; i++) {
var name = response.Restaurants[i].RestrntArea;
if (name) {
favoriteresultag +=
'<div data-role="collapsible" data-inset="false" class="my-collaspible"><h3>' +
name +
' <a class="icon-pencil-1 labelEditIcon "></a></h3></div>';
}
}
$("#result").append(favoriteresultag).trigger("create");
}
$(document).ready(function() {
$('.my-collaspible').bind('expand', function() {
alert('Expanded');
});
$('.my-collaspible').bind('collapse', function() {
alert('Collapsed');
});
});
Why the collapse and expand even'ts are being captured ??
Instead of document ready i tried with al the page events of mobile . But no luck .
From your fiddle I can't tell which version of jQM you are using. You have checked version 1.3 but then added the 1.4 css. Assumin version 1.4, I have updated your fiddle:
FIDDLE
Basically, you need to use event delegation to attach the events because the collapsibles do not exist at the time of the bind. Also the event names are actually collapsibleexpand and collapsiblecollapse.
So use on() instead of bind() by handling the event on the parent div and delegating it to all items with class my-collapsible that exist now or added dynamically:
$("#result").on('collapsibleexpand', '.my-collaspible', function () {
alert('Expanded');
});
$("#result").on('collapsiblecollapse', '.my-collaspible', function () {
alert('Collapsed');
});

knockout.js redirect in view model

I have the following code on cshtml page.
<div class="buttons">
<button type="button" id="export" class="export-inventory-button" onclick="location.href='#Url.Action("ExportInventory", "Inventory")'">EXPORT INVENTORY</button>
</div>
How do I make this work in my view model?
I think I almost got it, but need some help
<div class="buttons">
<button type="button" id="export" class="export-inventory-button" data-bind="click: exportInventory">EXPORT INVENTORY</button>
</div>
My viewmodel has this code:
function exportInventory() {
filtererGridData = vm.details;
var json = ko.mapping.toJSON(vm.details);
$.ajax({ url: '/Inventory/ExportInventory', type: 'POST' }).done(function (data) {
$('#export').html(data);
}).fail(function (data) {
toastr.warn('Could not export data, please contact LGL.');
});
}
I tried this, but I get errors:
function exportInventory() {
filtererGridData = vm.details;
var json = ko.mapping.toJSON(vm.details);
$.ajax({ url: 'location.href="#Url.Action("ExportInventory", "Inventory")"', type: 'POST' }).done(function (data) {
window.location.href = responseText.url;
$('#export').html(data);
}).fail(function (data) {
toastr.warn('Could not export data, please contact LGL.');
});
}
Can someone help me figure this out?
The way you're trying to pass in the url to the ajax call is probably not working the way you expect. Also, you wouldn't need the location.href= to be part of the url parameter in the $.ajax() call.
If your view model is coded in a script tag right in your cshtml page, you can try this:
<!-- cshtml razor view code for generating the html is above this line -->
<script>
var viewModel = {
function exportInventory() {
filtererGridData = vm.details;
var json = ko.mapping.toJSON(vm.details);
//allow razor to build a javascript string for you when it renders the html
//when the browser parses this script, it will just see a simple string
var myURL = '#Url.Action("ExportINventory", "Inventory")';
//pass your variable to the jQuery ajax call
$.ajax({ url: myURL, type: 'POST' }).done(function (data) {
window.location.href = responseText.url;
//this line of code would never be called because the browser has navigated away from this page...
$('#export').html(data);
}).fail(function (data) {
toastr.warn('Could not export data, please contact LGL.');
});
}
};
</script>
Load the page and view source. If the var myUrl = line is the correct URL to your controller as a string, then you know that razor kicked in and prepared that for you on render.

Jquery: How to make Slider working After Ajax call?

Hello!
i have a very nice Filter plugin i made with Jquery UI Slider, Here is the Full code And working Example:
http://jsbin.com/epikam/1/edit
Its working great, The Only problem is That After Ajax call it does not Change the Items..
Here is the Ajax call:
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: "q="+value+"&category="+cat+"&country="+country+"&page="+page,
success: function(data){
globalRequest = 0;
resultContainer.fadeOut('fast', function() {
resultContainer.html('');
for (var x in data) {
var html = '<li class="item" data-type="league2" data-id="id-'+x+'" style="position: relative;">';
html += '<label class="title">'+data[x].Title+'</label>';
html += '<img src="'+data[x].img+'">';
html += '<label class="price">New Price: '+data[x].newprice+'</label>';
html += '</li>';
resultContainer.append(html);
}
resultContainer.fadeIn('fast');
});
}
});
I tried to Use .live and .delegate With no success (Im not sure how\where to use it)
Any suggestions??
Thank you very much!!!
Eran.
Two things:
First, check that the success function is being called with something like console.log(data); in the success: callback and that there are not errors stopping the Ajax call from completing successfully. In the JavaScript console, check that the variable data has been correctly populated and contains the data you expect it to contain.
Secondly, use JQuery selectors instead of global variables within the ajax success call. E.g. use $("#resultContainer") (assuming the div has an id resultContainer) instead of the variable resultContainer.

Jquery Mobile - Dynamic Pages Accumulating in the DOM

I'm working on a simple Jquery Mobile application that does a search, presents results, and then allows you to click on a result to go to a dynamic detail page. On the detail page there is a collapsible list which uses an ajax call to get its content.
It appears to be working fine on the surface, but when I inspect it with Firebug I notice that every time you go to a detail page and expand the collapsible list, the ajax fires multiple times.
So, for instance, I do a search, go to the detail page, expand the collapsible list, the ajax fires once. I go back to the results page, click on another result, go to the detail page, expand the collapsible list, and the ajax fires twice, etc. Each time I expand the collapsible list, the ajax fires one more time...so if I look at 10 results, the ajax fires 10 times.
It would appear that the dynamic pages are accumulating in the DOM, and each time I click on the collapsible list, it's firing on all the selectors that have built up in the DOM (at least that's my theory).
How do I make sure that my ajax only fires once rather than multiple times?
I'm using Jquery Mobile 1.0.1 with Jquery 1.6.4. I'm using php to get the data.
Here's my code for the search page:
$('form#searchCompanies').submit(function(event) {
getSearchResultsCompanies();
return false;
});
function getSearchResultsCompanies() {
$.ajax({
type: "POST",
url: baseURL + 'server/searchCompanies.php',
data: $("form#searchCompanies").serialize(),
dataType: 'json',
success: function(results){
$('#companyList li').remove();
for ( var i=0; i < results.length; i++) {
$('#companyList').append('<li>' + results[i].CompanyName + '</li>');
}
$('#companyList').listview('refresh');
}
});
return false;
}
$('.companyDetail').live('click', function(event) {
//save companyid so that we can reference it on detail page
var companyid = $(this).attr('data-uid');
localStorage.setItem('thisCompanyId', companyid);
});
Here's the code for the detail page:
$('#companyDetailPage').live('pageshow', function(event) {
var companyid = localStorage.getItem('thisCompanyId');
$.ajax({
type: "POST",
url: baseURL + 'server/getCompanyDetail.php?companyid=' + companyid,
data: {companyid: companyid},
dataType: 'json',
success: function(company) {
$.each(company, function(index, company) {
$('#companyName').html(company.CompanyName);
//etc...pulls in more data to populate the page
});
}
});
//this is the call that fires multiple times
$('#companyContacts').live('expand', function(event) {
$('#companyContactList li').remove();
$.ajax({
type: "POST",
url: baseURL + 'server/getCompanyContacts.php?companyid=' + companyid,
dataType: 'json',
success: function(results){
for ( var i=0; i < results.length; i++) {
$('#companyContactList').append('<li>' + results[i].LastName + 'etc...more data</li>');
}
$('#companyContactList').listview('refresh');
}
});
return false;
});
});
The html div that gets populated looks like this:
<div data-role="collapsible" data-collapsed="true" id="companyContacts" class="cmdCompanyContacts">
<h3>Contacts (<span id="totalContacts"></span>)</h3>
<ul id="companyContactList" data-role="listview"><li></li></ul>
</div>
I've searched high and low for a resolution, and tried reworking my code from various angles, but I'm not able to solve this problem. Any help would be deeply appreciated. Thanks.
I had this problem too. I tried the suggestion found here, but still had the multiple event triggering problem after trying this. Here is what else I had to do. I changed it from this:
$(‘#myPage’).bind(‘pageinit’, function (event) {
$(‘#myButton’).live(‘click’, function (event, ui) {
to this:
$(‘#myPage’).bind(‘pageinit’, function (event) {
$(‘#myButton’).click(function (event, ui) {
Rather than using jquery live i would like to suggest you to use javascript function call when you click for the page change.Write your ajax call in that function so that its been called only once.Hope this helps

Resources