Cannot get jqueryui tabs to work properly in Ember view - jquery-ui

I'm trying to run up a little prototype in Ember.JS at the moment with a view to completely re-writing the UI of a web application as an Ember Application running against a WebAPI, but although I've managed to get Ember running OK, I cannot get jqueryui to initialise the tabs correctly.
It seems to work fine if within the view I put static data for tabs to be created from, but if I'm using dynamic data then it just doesn't work.
I have an Ember view template
<script type="text/x-handlebars" id="index">
<div id="tabs" class="ui-tabs">
<ul>
{{#each model}}
<li>
<span class="ui-icon ui-icon-person"></span>
<a {{bindAttr href="route"}} {{bindAttr title="tabTitle"}}><span>{{title}}</span></a>
</li>
{{/each}}
</ul>
{{#each model}}
<div {{bindAttr id="tabTitle"}}>
<p>
Retrieving Data - {{title}}
</p>
</div>
{{/each}}
</div>
</script>
and a view
App.IndexView = Ember.View.extend({
templateName: 'index',
didInsertElement: function () {
var tabs = $("#tabs").tabs();
}
});
and a model
App.Section = DS.Model.extend({
name: DS.attr('string'),
title: DS.attr('string'),
tabTitle: function () {
return 'tab-' + this.get('name');
}.property("name"),
route: function () {
return '#' + this.get('tabTitle');
}.property("tabTitle")
});
App.Section.FIXTURES = [
{
id: 1,
name: 'home',
title: 'Home'
},
{
id: 2,
name: 'users',
title: 'Users'
}
];
It appears to generate the HTML correctly (from checking in Firebug), but this does not work, where as if I replace the template with
<script type="text/x-handlebars" id="index">
<div id="tabs" class="ui-tabs">
<ul>
<li>
<span class="ui-icon ui-icon-person"></span>
<span>Home</span>
</li>
<li>
<span class="ui-icon ui-icon-person"></span>
<span>Users</span>
</li>
</ul>
<div id="tab-home">
<p>
Retrieving Data - Home
</p>
</div>
<div id="tab-users">
<p>
Retrieving Data - Users
</p>
</div>
</div>
</script>
it works perfectly.
I'm assuming that it's something to do with the DOM not being completely rendered by the time the tabs are initialised, but everything I can find says that didInsertElement is the place to do it, and I have had time to dig deeper yet.
I'd be grateful for any ideas.
Edit: I've managed to make this work in a fashion by doing the following:
App.IndexView = Ember.View.extend({
templateName: 'index',
didInsertElement: function () {
Ember.run.next(this, function () {
if (this.$('#tab-users').length > 0) {
var tabs = $('#tabs').tabs();
} else {
Ember.run.next(this.didInsertElement);
}
});
},
});
The problem with this is that 1) it requires me to know what one of the last elements that will be written to the view is called (and obviously with dynamic data I won't necessarily know that), so that I can keep checking for it, and 2) the inefficiency of this technique makes me want to scream!
In addition, we get a good old FoUC (Flash of Unstyled Content) after things have been rendered, but before we then get JQueryUI to style them correctly.
Any suggestions gratefully received.

It's still not nice... but this at least does work, and is reasonably efficient...
From Ember.js - Using a Handlebars helper to detect that a subview has rendered I discovered how to write a trigger, and because of the way that the run loop seems to work, inserting the trigger in the last loop on the page causes it to be called n times, but only after the loop is complete, so a quick state check "hasBeenTriggered" ensures that you only execute the delgate function once.
My code now looks like this:
<script type="text/x-handlebars" id="index">
<div id="tabs" class="ui-tabs">
<ul>
{{#each model}}
<li>
<span class="ui-icon ui-icon-person"></span>
<a {{bindAttr href="route"}} {{bindAttr title="tabTitle"}}><span>{{title}}</span></a>
</li>
{{/each}}
</ul>
{{#each model}}
<div {{bindAttr id="tabTitle"}}>
<p>
Retrieving Data - {{title}}
</p>
</div>
{{trigger "triggered"}}
{{/each}}
</div>
</script>
with the trigger
Ember.Handlebars.registerHelper('trigger', function (evtName, options) {
options = arguments[arguments.length - 1];
var hash = options.hash,
view = options.data.view,
target;
view = view.get('concreteView');
if (hash.target) {
target = Ember.Handlebars.get(this, hash.target, options);
} else {
target = view;
}
Ember.run.next(function () {
target.trigger(evtName);
});
});
and view
App.IndexView = Ember.View.extend({
templateName: 'index',
hasBeenTriggered: false,
triggered: function () {
if (!this.get("hasBeenTriggered")) {
var tabs = $('#tabs').tabs();
this.set("hasBeenTriggered", true);
}
}
});
I'd love to know if there's a better way of doing this, as this still doesn't get round the FOUC problem either (which again can be done with more JS hacks)... :(

Related

Vue js trucate property on array

I am trying use Vuejs's vue-truncate-collapsed property to add the read more and read less button. A Worker can have multiple services. Something like this. Services are stored as array.
<li v-for="item in worker.service_names">
{{ item}}
</li>
this works perfectly fine. But now what I want to do is display default 5 values(not sure how to add the length of 5) and if a worker has more than 5 services then read more button appear. I am not able to implement this on an array. Please help me figure out the issue. I am new to Vuejs.
<truncate
action-class="action"
clamp="..."
:length="5"
less="read less"
:text="<li>worker.service_names</li>"
type="html"
>
</truncate>
You could iterate over a computed list. If it is a short list the computed value will return a shortened list otherwise the full list.
var vm = new Vue({
el: '#app',
data: {
workers: ['A','B','C','D','E','F','G','H'],
showNum: 4,
short: true
},
computed: {
visibleWorkers(){
if(this.short){
return this.workers.slice(0,this.showNum)
}else{
return this.workers
}
}
},
methods: {
showMore(){
this.short=!this.short;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vue#2.6.11/dist/vue.js"></script>
<div id="app">
<div>
<ol>
<li v-for="item in visibleWorkers">
{{item}}
</li>
</ol>
<button #click="showMore">{{short?'show more':'hide'}}</button>
</div>
</div>

Jquerymobile - Listview -Ajax loading -CSS style

I am trying to load data using ajax, listview works charm on intialpage load, during ajax loading css is not loading.
nearly tried everything, like listview refresh,trigger etc..but nothing works out for me.
please help me
my code:
$('.more').live("click",function() {
var ID = $(this).attr("id");
var CASE = $(".case").attr("id");
var EXTRADATA = $(".extra_data").attr("id");
if(ID) {
$("#more"+ID).find("#loader").css('display', 'block');
$.ajax({
type: "POST",
url: "/ajax.php",
data: "lastpos=" + ID +"&case=" + CASE + "&extradata=" + EXTRADATA,
cache: false,
success: function(html){
$("#video_listing").append(html);
$("#more"+ID).remove(); // removing old more button
}
});
I had tried with
$('#video_listing').listview('refresh');
$(html).trigger('create');
.trigger( "enhance" );
Nothing works out...though lot of topics,covers this question,nothing worksout for me..please help
Here is a quick example: http://jsfiddle.net/Twisty/9SVPN/
JQuery:
$(document).ready(function() {
$('.more').live("click", function() {
$("#myList").append("<li>Added Item</li>");
$("#myList").listview("refresh");
});
});
HTML:
<html>
<head>
<title>Test</title>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h2>Test Page</h2>
</div>
<div data-role="content">
<ul data-role="listview" id="myList">
<li>Item 1</li>
</ul>
<a id="actionBtn" data-role="button" class="more">Add LI</a>
</div>
</div>
</body>
</html>
Your question does not define what HTML is returned or what your HTML looks like before the AJAX event, so I am making somassumptions that your returned data is wrapped within <li></li>. Then you want to perform the .listview("refresh") on the <ul data-role="listview"> or <ol data-role="listview"> itself.

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>

knockout.js mapping custom events

I try to build a simple blog application with knockout.js and rails.
(knockout v1.3 beta, knockout mapping plugin v2.0.2)
<h3>Posts</h3>
<ul data-bind="foreach: posts">
<li>
<input data-bind="value: title" />
</li>
</ul>
<script>
var posts = ko.mapping.fromJSON('<%= #posts.to_json.html_safe %>');
ko.applyBindings(posts);
</script>
this displays alle the posts from a rails app, no problem so far.
but now i want to add a custom event to the posts, e.g. a remove event.
i tried this:
<h3>Posts</h3>
<ul data-bind="foreach: posts">
<li>
<input data-bind="value: title" />
</li>
</ul>
<script>
var posts = ko.mapping.fromJSON('<%= #posts.to_json.html_safe %>', { remove: function() {
alert('working');
});
ko.applyBindings(posts);
</script>
but i get an error "remove is not defined"
any ideas?
you could just add the function to the posts viewModel, like this:
var posts = ko.mapping.fromJSON('<%= #posts.to_json.html_safe %>');
posts.remove = function() { alert('working'); }

JQuery and Custom Tabs using addClass & removeClass

So I am pretty new to JQuery and just spent 5 hours getting this working. If anyone has a better approach please I would love to hear.
That is my basic question how can it be done cleaner, more streamline?
What I did was used the minitabs plugin and what the code below will do is toggle custom tabs back and forth. I needed a way to have the one tab blue and the other gray depending what tab I was on. What I hit against was tab1 would stay blue even when I clicked on tab2, just was funky until this fixed it. As you can see it's not the cleanest approach but it works. I am sure if you want to try this out the minitab plugin can be had here.
http://minitabs.googlecode.com/files/jquery.minitabs.js
JQuery:
$(document).ready(function(){
$("#tabs").minitabs('slow', 'fade');
$("#tab1").click(function()
{
var $this = $(this);
if( $this.is('.removed') )
{
$this.removeClass('removed');
$this.addClass('selected');
$('#tab2').removeClass('selected');
$("#tab2").addClass('removed');
} else {
$('#tab2').removeClass('selected');
}
return false;
});
$("#tab2").click(function()
{
var $this = $(this);
if( $this.is('.removed') )
{
$this.removeClass('removed');
$this.addClass('selected');
$("#tab1").removeClass('selected');
$("#tab1").addClass('removed');
} else {
$('#tab1').removeClass('selected');
}
return false;
});
});
Body:
<div id="tabs">
<ul>
<li>tab-l</li>
<li>tab-r</li>
</ul>
<div id="quick-links">
<ul>
<li>Look at me getting myself all in a frenzy!</li>
</ul>
</div>
<div id="newsletter-link">
Sometimes it's would be nice if they reported the fun news!
</div>
</div>
I looked at this briefly, and didn't see any problems with this less-complex setup which takes advantage of minitabs automatically applying the class "current" to the currently selected tab:
<head>
<style type="text/css">
.tabs a {
background: grey;
}
.tabs a.current {
background: blue;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$("#tabs").minitabs('slow', 'fade');
});
</script>
</head>
<body>
<div id="tabs">
<ul class="tabs">
<li>tab-l</li>
<li>tab-r</li>
</ul>
<div id="quick-links">
<ul>
<li>Look at me getting myself all in a frenzy!</li>
</ul>
</div>
<div id="newsletter-link">
Sometimes it's would be nice if they reported the fun news!
</div>
</div>
</body>
For me that handles the case you describe perfectly.

Resources