initialize a listview outside of a page - jquery-mobile

I am building a single page application using jQuery Mobile.
In the header I have a "menu" button that opens a popup with a listview.
I would like to define this popup dialog and reuse it for all pages.
Reusing a popup outside a page works fine, but listview inside the popup does not get enhanced (because listview internally uses parent page to resolve links included in the list).
Question: is it possible to use a listview widget outside of a page? (I do understand that I might have to specify a base url for this to work, but I don't think that will be a problem).

No, its not possible. When you create a dynamic popup, which doesnt reside in a single page, IT WILL WORK, because popups were never meant to be used/page. But, listview on the other hand, requires the list to lie in a parent page. The refresh method of listview expects it to be in parent. Look at this function which is called when a listview refresh happens :
_createSubPages: function () {
var parentList = this.element,
parentPage = parentList.closest(".ui-page"), //<-- This line
parentUrl = parentPage.jqmData("url"),
parentId = parentUrl || parentPage[0][$.expando],
parentListId = parentList.attr("id"),
o = this.options,
dns = "data-" + $.mobile.ns,
self = this,
persistentFooterID = parentPage.find(":jqmData(role='footer')").jqmData("id"),
hasSubPages;
// blah blee blah
}).listview();
See the second line in the function. It expects a page to be there. Tough luck bro :)
PS : This is the closest i could get : http://jsfiddle.net/hungerpain/8qq62/1/
EDIT
Here's a hacky way. You could dynamically create a hidden <span/> in your data-role=page div and add the <ul/> in it. Then you could refresh it, after which you could move it to the dynamic popup. Then you'll have to remove that hidden span element. Here's the code :
$.extend({
"makePopup": function (array) { //you could add more if you want here, such as callbacks to the click function of the button,etc.
var $popup;
//creat popup element
$popup = $("<div/>", {
"data-role": "popup",
"data-theme": "a",
"data-overlay-theme": "a",
"data-transition": "pop"
}).popup();
//create list
$list = $("<ul/>", {
"data-role": "listview",
"id": "templist"
}).html(function () {
var li = [];
for (var i = 0; i < array.length; i++) {
li.push($("<li/>").html(array[i]));
}
return li;
})
//create close element
var $close = $("<a/>", {
"data-role": "button",
"html": "Close",
"href": "#",
"data-theme": "a"
}).on("click", function () {
//click event of close element
$(this).closest("[data-role=popup]").popup("close");
}).buttonMarkup();
//add a span to page, refresh list, etc
$.mobile.activePage.append("<span id='temp'></span>").find("#temp").hide().append($list).promise().done(function () {
$(this).find("#templist").listview().listview("refresh");
});
//create content div - makes a nice jQM page structure.
var $content = $("<div/>", {
"data-role": "content",
//move li to popup
}).append($("#temp").find("#templist"), $close);
//remove span
$("#temp").remove();
//append $close to $content, then append $content to $popup
$content.appendTo($popup)
return $popup;
}
});
And you could pass an array to this :
$.makePopup(["Sweet Child 'O Mine", "Summer of '69", "Smoke in the Water", "Enter Sandman", "I thought I've seen everything"]).popup("open");
Here's an updated demo : http://jsfiddle.net/hungerpain/8qq62/7/
But obviously this is hacky.

Related

jQuery UI Sortable with React.js buggy

I have a sortable list in React which is powered by jQuery UI. When I drag and drop an item in the list, I want to update the array so that the new order of the list is stored there. Then re-render the page with the updated array. i.e. this.setState({data: _todoList});
Currently, when you drag and drop an item, jQuery UI DnD works, but the position of the item in the UI does not change, even though the page re-renders with the updated array. i.e. in the UI, the item reverts to where it used to be in the list, even though the array that defines its placement has updated successfully.
If you drag and drop the item twice, then it moves to the correct position.
// Enable jQuery UI Sortable functionality
$(function() {
$('.bank-entries').sortable({
axis: "y",
containment: "parent",
tolerance: "pointer",
revert: 150,
start: function (event, ui) {
ui.item.indexAtStart = ui.item.index();
},
stop: function (event, ui) {
var data = {
indexStart: ui.item.indexAtStart,
indexStop: ui.item.index(),
accountType: "bank"
};
AppActions.sortIndexes(data);
},
});
});
// This is the array that holds the positions of the list items
var _todoItems = {bank: []};
var AppStore = assign({}, EventEmitter.prototype, {
getTodoItems: function() {
return _todoItems;
},
emitChange: function(change) {
this.emit(change);
},
addChangeListener: function(callback) {
this.on(AppConstants.CHANGE_EVENT, callback);
},
sortTodo: function(todo) {
// Dynamically choose which Account to target
targetClass = '.' + todo.accountType + '-entries';
// Define the account type
var accountType = todo.accountType;
// Loop through the list in the UI and update the arrayIndexes
// of items that have been dragged and dropped to a new location
// newIndex is 0-based, but arrayIndex isn't, hence the crazy math
$(targetClass).children('form').each(function(newIndex) {
var arrayIndex = Number($(this).attr('data-array-index'));
if (newIndex + 1 !== arrayIndex) {
// Update the arrayIndex of the element
_todoItems[accountType][arrayIndex-1].accountData.arrayIndex = newIndex + 1;
}
});
// Sort the array so that updated array items move to their correct positions
_todoItems[accountType].sort(function(a, b){
if (a.accountData.arrayIndex > b.accountData.arrayIndex) {
return 1;
}
if (a.accountData.arrayIndex < b.accountData.arrayIndex) {
return -1;
}
// a must be equal to b
return 0;
});
// Fire an event that re-renders the UI with the new array
AppStore.emitChange(AppConstants.CHANGE_EVENT);
},
}
function getAccounts() {
return { data: AppStore.getTodoItems() }
}
var Account = React.createClass({
getInitialState: function(){
return getAccounts();
},
componentWillMount: function(){
AppStore.addChangeListener(this._onChange);
// Fires action that triggers the initial load
AppActions.loadComponentData();
},
_onChange: function() {
console.log('change event fired');
this.setState(getAccounts());
},
render: function(){
return (
<div className="component-wrapper">
<Bank data={this.state.data} />
</div>
)
}
});
The trick is to call sortable('cancel') in the stop event of the Sortable, then let React update the DOM.
componentDidMount() {
this.domItems = jQuery(React.findDOMNode(this.refs["items"]))
this.domItems.sortable({
stop: (event, ui) => {
// get the array of new index (http://api.jqueryui.com/sortable/#method-toArray)
const reorderedIndexes = this.domItems.sortable('toArray', {attribute: 'data-sortable'})
// cancel the sort so the DOM is untouched
this.domItems.sortable('cancel')
// Update the store and let React update (here, using Flux)
Actions.updateItems(Immutable.List(reorderedIndexes.map( idx => this.state.items.get(Number(idx)))))
}
})
}
The reason jQuery UI Sortable doesn't work with React is because it directly mutates the DOM, which is a big no no in React.
To make it work, you would have to modify jQuery UI Sortable so that you keep the DnD functionality, but when you drop the element, it does not modify the DOM. Instead, it could fire an event which triggers a React render with the new position of the elements.
Since React uses a Virtual DOM, you have to use the function React.findDOMNode() to access an actual DOM element.
I would call the jQuery UI function inside the componentDidMount method of your component because your element has to be already rendered to be accessible.
// You have to add a ref attribute to the element with the '.bank-entries' class
$( React.findDOMNode( this.refs.bank_entries_ref ) ).sortable( /.../ );
Documentation - Working with the browser (everything you need to know is here)
Hope that makes sense and resolves your issue

Does Dart have childSelector in event function like jQuery on()?

Does Dart have childSelector in event function like jQuery on()? Because I want fire contextmenu event only if mouse hover specific element type.
This is my javascript code.
var $contextMenu = $("#context-menu");
$("body").on("contextmenu", "table tr", function(e) {
$contextMenu.css({
display: "block",
left: e.pageX,
top: e.pageY });
return false;
});
But I don't know how to check if hover "table tr" in my Dart code.
var body = querySelector('body');
var contextMenu =querySelector('#context-menu');
// fire in everywhere
body.onContextMenu.listen((e) {
e.preventDefault();
contextMenu.style.display = 'block';
contextMenu.style.left = "${e.page.x}px";
contextMenu.style.top = "${e.page.y}px";
}
You can filter events :
body.onContextMenu.where((e) => e.target.matchesWithAncestors("table tr"))
.listen((e) {
e.preventDefault();
contextMenu.style.display = 'block';
contextMenu.style.left = "${e.page.x}px";
contextMenu.style.top = "${e.page.y}px";
});
the problem is the following:
$("body") gives you a set of elements that does not change. The `.on(..., 'sub selector') however is actually bad, because it checks the subselector against the target of the event EVERY TIME for every event.
I see two solutions here:
The first is to select all children and add the event listener to all of the elements:
var body = querySelector('body');
body.querySelectorAll('table tr')... onContextMenu...
But this will not work if you insert tr into the table later.
The other way is to check the .target of your event and see if it's a tr and if its in your table. I hope this already helps. If you need more detailed help let me know!
Regards
Robert

Angular view gets out of sync with model when dragging items from one list to another

I have created a custom directive that allows me to connect multiple sortable lists via drag and drop using angular js and jquery ui. The way it should work is the following:
When drag starts, keep track of the initial position of the item in the array and the value of ng-model for that sortable
When the drag ends, if the item is received to a different list, keep track of the ng-model of that list and the target position of the element
Broadcast an event with that data so that the controller can change the positions of the items from one array to another
The problem is that once I move one item from one list to another, even though the items in the arrays go where they should, in the view some HTML elements disappear.
Here is the sortable directive:
app.directive('mySortable',function(){
return {
link:function(scope,el,attrs){
var options = {};
if(attrs.connectWith)
{
options.connectWith = attrs.connectWith;
}
el.sortable(options);
el.disableSelection();
el.on("sortstart", function(event, ui){
var from_index = angular.element(ui.item).scope()?angular.element(ui.item).scope().$index : 0;
var from_model = angular.element(ui.item.parent()).attr('ng-model');
ui.item.scope().sortableData = {from_index: from_index, from_model: from_model};
});
el.on("sortreceive", function(event, ui){
ui.item.scope().sortableData.to_index = el.children().index(ui.item);
ui.item.scope().sortableData.to_model = angular.element(el).attr('ng-model');
});
el.on( "sortdeactivate", function( event, ui ) {
var to_model = angular.element(el).attr('ng-model');
var from = angular.element(ui.item).scope()?angular.element(ui.item).scope().$index : 0;
var to = el.children().index(ui.item);
if(to>=0){
scope.$apply(function(){
if(from>=0){
scope.$emit('list-sorted', {from:from,to:to}, ui.item.scope());
}else{
scope.$emit('list-appended', {to:to, name:ui.item.text()});
ui.item.remove();
}
})
}
} );
}
}
})
And here is the controller logic that handles it's event:
$scope.$on('list-sorted', function(ev, val, task_scope){
var sd = task_scope.sortableData;
if(sd.to_model)
{
$timeout(function(){
$scope[sd.to_model].splice(sd.to_index, 0, $scope[sd.from_model].splice(sd.from_index, 1)[0]);
});
}
else
{
$timeout(function(){
$scope[sd.from_model].splice(val.to, 0, $scope[sd.from_model].splice(val.from, 1)[0]);
});
}
console.log($scope);
});
What's wrong?
Example JS Fiddle
It seems that the controller logic comports an error.
Is it fine like this:
var sd = item_scope.sortableData;
// If the item is supposed to be dropped to a different list, move it from one list to another
if(sd.to_model)
{
console.log("to a different list", val)
$timeout(function(){
$scope[sd.to_model].splice(val.to, 0, $scope[sd.from_model].splice(sd.from_index, 0));
});
}
else
{
console.log("to the same list")
$timeout(function(){
$scope[sd.from_model].splice(val.to, 0, $scope[sd.from_model].splice(val.from, 1)[0]);
});
}

Knockout bindings are not working with jsTree

I'm trying to get jsTree (1.0-rc3) working with Knockout.js (2.2.1).
See example jsFiddle: http://jsfiddle.net/adeconsulting/qfr6A/
Note: I've included several JS resources in the Fiddle to match as close as possible my Visual Studio project, in case there's a conflict between libraries which might be causing this problem.
Run the Fiddle and navigate through the jsTree, it's a list of servers by their physical location and type. It helps to have Firebug's console open so you can see the ajax calls and responses. When you click a leaf node, an ajax call is made to retrieve the server details and display a form whose values use Knockout bindings. I hide the form when a non-leaf node is selected.
It works the first time you click a leaf node. After that, Knockout does not update the form for leaf node clicks. However, if you happen to click the Edit button, then all of a sudden the most recent server details ARE displayed.
I'm thinking that there's a conflict between jsTree and Knockout bindings, but don't know where to start troubleshooting what that might be.
Since stackoverflow apparently requires at least one code block, here's the JavaScript portion of the Fiddle:
// Global vars:
var prevJsTreeNodeId = null;
var serverModelBindingsApplied = false;
var serverLoadInProgress = false;
/*
* The knockout.js view model
*/
var ServerViewModel = function () {
// Data
var self = this;
self.IsReadOnly = ko.observable(true); // the form's input mode
self.btnEditSave = ko.observable("Edit"); // the Edit/Save button text
self.Server = ko.observable({}); // the Server object
// Operations
self.setEditable = function () {
self.IsReadOnly(false);
self.btnEditSave("Save");
};
self.setReadOnly = function () {
self.IsReadOnly(true);
self.btnEditSave("Edit");
};
self.doEditSave = function () {
var flag = self.IsReadOnly();
if (flag) {
// switch to Edit mode
self.setEditable();
}
else {
// switch back to readOnly
self.setReadOnly();
}
};
// use ajax to update the knockout.js view model's Server object for the specified server name
self.load = function (serverName) {
if (!serverLoadInProgress) {
serverLoadInProgress = true;
// use ajax to retrieve the server's details
var data = {
json: JSON.stringify({
ServerName: serverName,
PrimaryIP: "1.2.3.4",
BrandDesc: "Dell",
OSDesc: "Windows 2003 Server",
Location: "xyz"
}),
delay: 1
};
$.ajax({
url:"/echo/json/",
data:data,
type:"POST",
success:function(response)
{
console.log(response);
window.ServerViewModelInstance.Server = ko.mapping.fromJS(response);
// apply bindings the first time we retrieve a Server object
if (!serverModelBindingsApplied) {
ko.applyBindings(window.ServerViewModelInstance,
document.getElementById('servercontent'));
serverModelBindingsApplied = true;
}
else {
// hmmm... updating the view model's .Server property doesn't trigger the
// form to be updated, yet if we click the Edit button, the new values
// suddenly appear, so try emulating that here...
self.setReadOnly();
}
}
});
serverLoadInProgress = false;
}
};
}; // ServerViewModel
/*
* document load
*/
$(function () {
// configure the jsTree
$("#divtree")
.jstree({
"themes": { "theme": "default", "dots": true, "icons": true },
"plugins": ["themes", "html_data", "ui", "types"],
"types": {
"type_attr": "tag", // the attribute which contains the type name
"max_depth": -2, // disable depth check
"max_children": -2, // disable max children check
"valid_children": ["root"],
"types": {
"root": {
"valid_children": ["level1"]
},
"level1": {
"valid_children": ["level2"],
"start_drag": false,
"move_node": false,
"delete_node": false,
"remove": false
},
"level2": {
"valid_children": ["leaf"],
// use the theme icon for the level2 nodes
"start_drag": false,
"move_node": false,
"delete_node": false,
"remove": false
},
"leaf": {
"valid_children": "none"
}
}
}
});
// register to receive notifications from #divtree when a jsTree node is selected
$("#divtree").bind("select_node.jstree", function (event, data) {
// data.rslt.obj is the jquery extended node that was clicked
var key = data.rslt.obj.attr("key");
var id = data.rslt.obj.attr("id");
if (id == prevJsTreeNodeId) {
// user clicked the same node, nothing to do
return;
}
prevJsTreeNodeId = id;
// when a jsTree node is selected, reset the knockout.js view model to read only
window.ServerViewModelInstance.setReadOnly();
var idx = key.indexOf("Server");
if (idx === 0) { // "Server|servername"
// show the "servercontent" div
$("#servercontent").show();
// display the server details
var serverName = key.substr(idx + 7, key.length);
window.ServerViewModelInstance.load(serverName);
}
else {
// hide the "servercontent" div
$("#servercontent").hide();
}
});
// hide the "servercontent" div
$("#servercontent").hide();
// instantiate the knockout.js view model
window.ServerViewModelInstance = new ServerViewModel();
}); // document ready
// initialization timer routine to select the main jsTree node
setTimeout(function () {
// open the root node
$.jstree._reference("#divtree").open_node("#root");
}, 500);
Sorry for my bad formatting below - this editor is not my friend... :-/
If I understand you right, the detail panel for a clicked tree node isn't updated with the correct data - right?
Try to do the following:
change:
window.ServerViewModelInstance.Server = ko.mapping.fromJS(response);
to: window.ServerViewModelInstance.Server(response);
(e.g. not overwriting the initial ko.observable which you only binds once, instead updating its values)
and in view where you bind to the observables..
for instance instead of: ... "value: Server.ServerName, ...
change it to: ... "value: Server().ServerName, ...
(e.g executing the function before accessing the property)
It works and updates the form when clicking on a new server name node in the tree (tried in firefox)
A copy of your example with the modified code can be found at: http://jsfiddle.net/RZ92g/2/

jQuery-UI Dialog Buttons - pass argument to btn click function

I'm a begginer jQuery dev, and I'm using the jQuery UI dialog to show up properties of an object (whatever).
var $dialog = $('<div></div>')
.html('This dialog will show every time!')
.dialog({
autoOpen: false,
title: 'Properties'
});
So this is the dialog, and let's say I have a FOR structure in which I add properties (p tags) and for some of those properties I want a button.
var dialogHtml = "";
var dialog_buttons = {};
for (var key in d.properties){
var str;
var str = '<p>' + something + '</p>';
if (condition){
dialog_buttons[key] = function()
{ functionName(key); };
}
dialogHtml = dialogHtml + str;
}
$dialog.dialog( "option", "buttons", dialog_buttons );
$dialog.dialog('open');
And somewhere else I have the function:
function functionName(key){
// something something
}
This is where I have the problem: the key variable that's passed to the function... when the button is called the key is the last value from the iteration.
Let's say we have keys 1, 2, 3, 4 then when the button is clicked, the key parameter will be 4.
I want when I click a button from the dialog, to know which button was pressed.
Can anybody help me?
Thanks!
Using the event data from the click event (see here)
$('#btn').click(function(e) {
functionName(e.target);
});
Explanation of Event.Target

Resources