Render partial later after page loads - ruby-on-rails

Using Rails 3.2. Let's say I have the following view:
<div class="content">
<div class="main">
<h1><%= #shop.name %></h1>
<p><%= #shop.description %></p>
</div>
<div class="sidebar">
<%= render 'teasers' %>
</div>
</div>
Is there a way to just load the page first, then load the teasers later? Reason being so is because teasers takes some time to query (I have already optimized the query).

I personaly have a pre-defined system for this kind of behavior:
This (coffeescript) Javascript code is executed at each rendering of a page:
$('.ajax_load').each (index, element) ->
e = $(element)
$.get e.data('url'), (data) =>
$(document).replace(e, data)
So each element in my page responding to the class "ajax_load" is actually called by ajax, example:
%div.ajax_load{ data: { url: users_path } }
This will display at first a div with a class ajax_load, and will send a request to users_path and replace the div with the response's content.
This is translated coffeescript:
$('.ajax_load').each(function(index, element) {
var e,
_this = this;
e = $(element);
return $.get(e.data('url'), function(data) {
return $(document).replace(e, data);
});
});

How about removing the teasers partial from the view and initially just displaying the page without it. Then using javascript, make an AJAX call to the server.
You can use wiselinks to simplify your life.

Related

redirect to action asp.net MVC

I want to redirect to an action afer the execution of create method
so the create method returns this:
return Json(new
{
Data = base.RenderView("_Forme ", model),
Message = (string)TempData[TEMP_DATA_MESSAGE_KEY],
Result = (AjaxResultType)TempData[TEMP_DATA_CODE_KEY]
}, JsonRequestBehavior.AllowGet);
}
Layout page:
<div> #Html.Partial("_Forme") </div>
#if (#Model.nouveau==false)
{
<div> #Html.Partial("_Onglet") </div>
<div> #Html.Partial("_Details") </div>
}
**In the View: _Forme.cshtml **
<a href="#Url.Action("Create", "Uneform")"
#if (Model.nouveau==true)
{ Create}
{ Update }
</a>
I want to be able to refrech the layout page and display all the partial views.
I already try redirect to action using javascript didn't work,any help
If you want to refresh only some part of the layout page, wrap that in a container div and make an ajax call to get the new markup for this area
<div id="updatable">
#if (#Model.nouveau==false)
{
<div> #Html.Partial("_Onglet") </div>
<div> #Html.Partial("_Details") </div>
}
</div>
and in your ajax call's success event, you may use the $.load method
$("#updatable").load("/Home/GetUpdatedHeader");
Assuming GetUpdatedHeader action method return a partial view which has the other 2 partials in it.
If you simply want to reload the same page, you can do this in javascript.
window.location.href = window.location.href;
You can do this is in your ajax call's success event.
If you want to redirect to another action/page
window.location.href ="/Home/Index"; //Replace this value with your url
You may also send the url for your new page in the json response(You can use the UrlHelper to build the urls) and use that for the redirect.

TypeError: Cannot set property 'chat_room_id' of undefined when using ng-if

I'm running into a bit of a road block here.
I'm working on a chat feature, which is currently within a rails partial in the application.html.erb file.
What I'm looking to do is have a list of a user's friends display in the chat area initially. When the user clicks on a friend's name, the corresponding chat room opens and the messages between the user and friend are displayed. If the user wishes to exit the chat, and view his friends list again, the user would simply click a button (currently "View Friends").
I am currently toggling between friends and rooms/messages using the ng-if directive.
I have not completely set this up yet, so I know there are bugs. I have created user friendships within rails, set up my REST API in rails, and can GET and POST resources via Angular and Restangular.
However, the issue at hand is that ever since I implemented the ng-if directives in the partial, I am getting the following error:
TypeError: Cannot set property 'chat_room_id' of undefined
If I am to remove the ng-if directives and all of the corresponding $scope.messagesVisible and $scope.friendsVisible variable references within the controller, the form submit works, so I know it has something to do with my implementation of the ng-if directives, and the fact that newMessage is undefined, but I'm not sure why.
I suspect it has something to do with Angular promises or my lack of understanding in regards to both Angular promises and the ng-if directive, but if anyone could shed some light on why this may be happening (and offer a solution) that would be amazing.
Thanks, guys!
Code below (please excuse terrible styling - it's a placeholder)
rails_partial:
<section ng-app="atmosphere" ng-controller="AtmoChatCtrl" style="position:relative; top:32%; float:right; right:5px; margin-bottom:10px; margin-top:30px;">
<div ng-if="friendsVisible" style="position:relative; left:35px; width:100px;">
<% user_friendships.each do |friendship| %>
<ul>
<% friend = friendship.friend %>
<% if friendship.accepted? %>
<li style="cursor:pointer;" ng-click="setChatAttributes(<%= friend.id %>, <%= current_user.id %> );"><%= friend.name %></li>
</ul>
<% end %>
<% end %>
</div>
<div ng-if="messagesVisible" style="position:absolute; top:60%; width: 150px; height:40%; right:-80px; margin-top:100px">
<div>
<p ng-repeat="message in messages">{{message.user_id}}: {{message.body}}</p>
<form ng-submit="saveMessage();">
<input type="text" ng-model="newMessage.body">
</form>
</div>
</div>
<div style="position:absolute; top:300px;">
<button ng-if="messagesVisible" ng-click="viewFriends();">View Friends</button>
</div>
</section>
<%= javascript_include_tag "angular/application" %>
<%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular-resource.min.js" %>
angular_controller:
angular.module('AtmoChatCtrl', [])
.controller('AtmoChatCtrl', ['$scope', '$resource', '$interval','Pusher','Restangular', function ($scope, $resource, $interval, Pusher, Restangular) {
$scope.baseMessages = Restangular.one('api/chat_rooms', 2).all('chat_messages');
$scope.roomId = '2';
$scope.messagesVisible = false;
$scope.friendsVisible = true;
console.log("SET ROOM");
$interval(function(){
$scope.baseMessages.getList().then(function(messages) {
$scope.messages = messages;
});
console.log("POLLING");
}, 1000);
$scope.saveMessage = function() {
$scope.newMessage.chat_room_id = $scope.roomId;
$scope.newMessage.user_id = $scope.userId;
$scope.baseMessages.post($scope.newMessage).then(function(newMessage){
$scope.messages.push(newMessage);
console.log("SAVED");
})
}
$scope.setChatAttributes = function(roomId, userId) {
$scope.baseMessages = Restangular.one('api/chat_rooms', roomId).all('chat_messages');
$scope.roomId = roomId;
$scope.userId = userId;
$scope.messagesVisible = true;
$scope.friendsVisible = false;
console.log(roomId)
console.log(userId)
}
$scope.viewFriends = function() {
$scope.friendsVisible = true;
$scope.messagesVisible = false;
}
}]);
NVM. I'm an idiot. Solved by setting $scope.newMessage = {}; after the first $scope.friendsVisible = true;

backbone view passed to jQuery Mobile

I've been trying to use backbonejs and jqm together.
I can render the main page alright. The page has a list that the user can tap on. The item selected should show a detail page with info on the list item selected. The detail page is a backbone view with a template that's rendered in the item's view object.
The detail's view .render() produces the html ok and I set the html of the div tag of the main page to the rendered item's detail markup. It looks like this:
podClicked: function (event) {
console.log("PodListItemView: got click from:" + event.target.innerHTML + " id:" + (this.model.get("id") ? this.model.get("id") : "no id assigned") + "\n\t CID:" + this.model.cid);
var detailView = new PodDetailView({ model: this.model });
detailView.render();
},
The detail view's render looks like this:
render: function () {
this.$el.html(this.template({ podId: this.model.get("podId"), isAbout_Name: this.model.get("isAbout_Name"), happenedOn: this.model.get("happenedOn") }));
var appPageHtml = $(app.el).html($(this.el));
$.mobile.changePage(""); // <-- vague stab in the dark to try to get JQM to do something. I've also tried $.mobile.changePage(appPageHtml).
console.log("PodDetailView: render");
return this;
}
I can see that the detail's view has been rendered on the page by checking Chrome's dev tools html editor but it's not displaying on the page. All I see is a blank page.
I've tried $.mobile.changePage() but, without an URL it throws an error.
How do I get JQM to apply it's class tags to the rendered html?
the HTML and templates look like this:
<!-- Main Page -->
<div id="lessa-app" class="meditator-image" data-role="page"></div>
<!-- The rest are templates processed through underscore -->
<script id="app-main-template" type="text/template">
<div data-role="header">
<h1>#ViewBag.Title</h1>
</div>
<!-- /header -->
<div id="main-content" data-role="content">
<div id="pod-list" data-theme="a">
<ul data-role="listview" >
</ul>
</div>
</div>
<div id="main-footer" data-role='footer'>
<div id="newPod" class="ez-icon-plus"></div>
</div>
</script>
<script id="poditem-template" type="text/template">
<span class="pod-listitem"><%= isAbout_Name %></span> <span class='pod-listitem ui-li-aside'><%= happenedOn %></span> <span class='pod-listitem ui-li-count'>5</span>
</script>
<script id="page-pod-detail-template" type="text/template">
<div data-role="header">
<h1>Pod Details</h1>
</div>
<div data-role="content">
<div id='podDetailForm'>
<fieldset data-role="fieldcontain">
<legend>PodDto</legend>
<label for="happenedOn">This was on:</label>
<input type="date" name="name" id="happenedOn" value="<%= happenedOn %>" />
</fieldset>
</div>
<button id="backToList" data-inline="false">Back to list</button>
</div>
<div data-role='footer'></div>
</script>
Thanks in advance for any advice... is this even doable?
I've finally found a way to do this. My original code has several impediments to the success of this process.
The first thing to do is to intercept jquerymobile's (v.1.2.0) changePage event like this:
(I've adapted the outline from jqm's docs and left in the helpful comments: see http://jquerymobile.com/demos/1.2.0/docs/pages/page-dynamic.html
)
$(document).bind("pagebeforechange", function (e, data) {
// We only want to handle changePage() calls where the caller is
// asking us to load a page by URL.
if (typeof data.toPage === "string") {
// We are being asked to load a page by URL, but we only
// want to handle URLs that request the data for a specific
// category.
var u = $.mobile.path.parseUrl(data.toPage),
re = /^#/;
// don't intercept urls to the main page allow them to be managed by JQM
if (u.hash != "#lessa-app" && u.hash.search(re) !== -1) {
// We're being asked to display the items for a specific category.
// Call our internal method that builds the content for the category
// on the fly based on our in-memory category data structure.
showItemDetail(u, data.options); // <--- handle backbone view.render calls in this function
// Make sure to tell changePage() we've handled this call so it doesn't
// have to do anything.
e.preventDefault();
}
}
});
The changePage() call is made in the item's list backbone view events declaration which passes to the podClicked method as follows:
var PodListItemView = Backbone.View.extend({
tagName: 'li', // name of (orphan) root tag in this.el
attributes: { 'class': 'pod-listitem' },
// Caches the templates for the view
listTemplate: _.template($('#poditem-template').html()),
events: {
"click .pod-listitem": "podClicked"
},
initialize: function () {
this.model.bind('change', this.render, this);
this.model.bind('destroy', this.remove, this);
},
render: function () {
this.$el.html(this.listTemplate({ podId: this.model.get("podId"), isAbout_Name: this.model.get("isAbout_Name"), happenedOn: this.model.get("happenedOn") }));
return this;
},
podClicked: function (event) {
$.mobile.changePage("#pod-detail-page?CID='" + this.model.cid + "'");
},
clear: function () {
this.model.clear();
}
});
In the 'showItemDetail' function the query portion of the url is parsed for the CID of the item's backbone model. Again I've adapted the code provided in the jquerymobile.com's link shown above.
Qestion: I have still figuring out whether it's better to have the code in showItemDetail() be inside the view's render() method. Having a defined function seems to detract from backbone's architecture model. On the other hand, having the render() function know about calling JQM changePage seems to violate the principle of 'separation of concerns'. Can anyone provide some insight and guidance?
// the passed url looks like #pod-detail-page?CID='c2'
function showItemDetail(urlObj, options) {
// Get the object that represents the item selected from the url
var pageSelector = urlObj.hash.replace(/\?.*$/, "");
var podCid = urlObj.hash.replace(/^.*\?CID=/, "").replace(/'/g, "");
var $page = $(pageSelector),
// Get the header for the page.
$header = $page.children(":jqmData(role=header)"),
// Get the content area element for the page.
$content = $page.children(":jqmData(role=content)");
// The markup we are going to inject into the content area of the page.
// retrieve the selected pod from the podList by Cid
var selectedPod = podList.getByCid(podCid);
// Find the h1 element in our header and inject the name of the item into it
var headerText = selectedPod.get("isAbout_Name");
$header.html("h1").html(headerText);
// Inject the item info into the content element
var view = new PodDetailView({ model: selectedPod });
var viewElHtml = view.render().$el.html();
$content.html(viewElHtml);
$page.page();
// Enhance the listview we just injected.
var fieldContain = $content.find(":jqmData(role=listview)");
fieldContain.listview();
// We don't want the data-url of the page we just modified
// to be the url that shows up in the browser's location field,
// so set the dataUrl option to the URL for the category
// we just loaded.
options.dataUrl = urlObj.href;
// Now call changePage() and tell it to switch to
// the page we just modified.
$.mobile.changePage($page, options);
}
So the above provides the event plumbing.
The other problem I had was that the page was not set up correctly. It's better to put the page framework in the main html and not put it in an underscore template to be rendered at a later time. I presume that avoids issues where the html is not present when jqm takes over.
<!-- Main Page -->
<div id="lessa-app" data-role="page">
<div data-role="header">
<h1></h1>
</div>
<!-- /header -->
<div id="main-content" data-role="content">
<div id="pod-list" data-theme="a">
<ul data-role="listview">
</ul>
</div>
</div>
<div id="main-footer" data-role='footer'>
<div id="main-newPod" class="ez-icon-plus"></div>
</div>
</div>
<!-- detail page -->
<div id="pod-detail-page" data-role="page">
<div data-role="header">
<h1></h1>
</div>
<div id="detail-content" data-role="content">
<div id="pod-detail" data-theme="a">
</div>
</div>
<div id="detail-footer" data-role='footer'>
back
</div>
</div>

How to make this javascript unobtrusive?

I have this javascript code, from google charts api right in the bottom of my view :
<div id='visualization'></div>
...
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable(<%=raw #pie_gender %>)
// Create and draw the visualization.
new google.visualization.PieChart(document.getElementById('visualization')).
draw(data, {title:"Men and Women"});
}
google.setOnLoadCallback(drawVisualization);
</script>
I've tried to put this js code in my assets folder under a .js file, and include it in my headers, as well as replacing <%=raw #pie_gender %> with this.getAttribute('data-message') and putting my div as ', but then i get a javascript error "getAttribute" does not exist for object window
I have also tried to pass my array as an input argument like : onload="drawVisualization(<%=raw #pie_gender %>), but then I get "Error: Not an array"
What might I be doing wrong ?
EDIT
#pie_gender = [['Gender', 'Occurences']['M', 10]['F', 5]]
Based on example from google
EDIT 2
If i print the json output
<% logger.debug "Pie Gender : #{#pie_gender.to_json}" %>
<div id="visualization" onload="drawVisualization(<%= #pie_gender.to_json %>)" > </div>
,it seems just fine :
Pie Gender : [["Gender","Receipts"],["",25000],["F",8658]]
but it seems that something happens while sending this as an argument to my js function, because it still says that message is not an array :
function drawVisualization(message) {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable(message);
// Create and draw the visualization.
new google.visualization.PieChart(document.getElementById('visualization')).
draw(data, {title:"Men and Women"});
}
google.setOnLoadCallback(drawVisualization);
To workaround this, I inserted my javascript code in a partial
_googlescript.html.erb
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable(<%=raw data_array %>)
// Create and draw the visualization.
new google.visualization.PieChart(document.getElementById('visualization')).
draw(data, {title:"Men and Women"});
}
google.setOnLoadCallback(drawVisualization);
</script>
in my view I rendered the partial in the bottom of the page, and removed the onload, which just seemed not to be doing a thing... :
<div id="visualization" > </div>
...
<%= render partial: 'shared/googlescript', locals: {data_array:#pie_gender} %>
Now i can see the chart again...but i still feel there is a better answer to my question.

Show feedback to a user when loading content though ajax

I'm using the jquery tab plugin with the same results that are on jquery ui site (link text).
The problem is that I want to change the tab label to something like "Loading" when the Ajax request is waiting for a response. How shall I achieve that?
Edit:
What I have now:
<div id="tabs">
<ul>
<li>User Profile</li>
<li>Edit</li>
<li>Delete AccountT</li>
</ul>
<div id="tabs-1">
<% Html.RenderPartial("UserProfile", Model); %>
</div>
</div>
and on javascript I just have the following code:
<script type="text/javascript">
$(function () {
$("#tabs").tabs({
});
});
</script>
What i want is to show a loading message inside the div of the active tab.
According to the widget doc, ajax should work outside the box if your href is an actual link :
To customize loading message, you can use the spinner option :
Fetch external content via Ajax for
the tabs by setting an href value in
the tab links. While the Ajax request
is waiting for a response, the tab
label changes to say "Loading...",
then returns to the normal label once
loaded.
<script>
$(function() {
$( "#tabs" ).tabs({
spinner: "<em>My Loading Msg</em>",
ajaxOptions: {
error: function( xhr, status, index, anchor ) {
$( anchor.hash ).html(
"Couldn't load this tab. We'll try to fix this as soon as possible. " +
"If this wouldn't be a demo." );
}
}
});
});
</script>
Why don't you just set the tab label to "loading" onclick and change it to whatever you want once you get a response back from your AJAX?
$(function () {
$("#tabs").tabs();
$("#tab1").click(function() {
$(this).val("Loading...");
$.ajax({
blablabla...
success: function() {
$("#tab1").val("Tab 1");
}
});
});
This should give you an idea, obviously the function could be written better to act on each tab.
I think what you are after already exists in the jquery ui for Tabs.
The HTML content of this string is
shown in a tab title while remote
content is loading.
http://jqueryui.com/demos/tabs/#option-spinner
Hope this helps!
From your example am I correct in assuming that you want to navigate to another page when the user clicks on either of the second two tabs, but you want a loading message to be displayed while you are waiting for the next tab to load?
If so, you could do it by keeping a loading message in the other tabs like so:
<input type="hidden" id="modelId" value="<%=Model.Id%>" />
<div id="tabs">
<ul>
<li>
User Profile
</li>
<li>
Edit
</li>
<li>
Delete AccountT
</li>
</ul>
<div id="tabs-1">
<% Html.RenderPartial("UserProfile", Model); %>
</div>
<div id="tabs-2">
<p>Loading, please wait...</p>
</div>
<div id="tabs-3">
<p>Loading, please wait...</p>
</div>
</div>
And doing the redirection to your other pages in your javascript, doing it something like this:
$(document).ready(document_ready);
function document_ready()
{
$("tabs").bind("tabsselect", onTabSelected);
}
function onTabSelected(event, ui)
{
var modelId = $("#modelId").val();
switch (ui.panel.id)
{
case "tabs-2":
window.location.href = "/User/EditUser/" + modelId;
break;
case "tabs-3":
window.location.href = "/User/Delete/" + modelId;
break;
}
}

Resources