Appcelerator - Programmatic Toggle of Switch in Custom TableViewRow - javascript

I have a custom TableViewRow with a title and switch like below:
rowFilter.xml
<TableViewRow id="rowFilter">
<View id="vwItemHeader">
<Label id="lblItemHeader"></Label>
</View>
<View id="vwFilterStatus">
<Switch id="swtFilterStatus" onChange="swtFilterStatusChange"></Switch>
</View>
</TableViewRow>
rowFilter.js
var args = arguments[0] || {};
var swtFilterStatusChange_callback;
initialize();
function initialize() {
// Initialize filter row UI
$.lblItemHeader.text = args.title;
$.swtFilterStatus.value = args.value;
// Callback
swtFilterStatusChange_callback = args.callback;
};
In a view I call Browse, I programmatically add these custom rows as follows:
var args = { title: item.title, value: item.value, callback: swtFilterStatusChanged, };
var newRow = Alloy.createController('rowFilter', args).getView('rowFilter');
This works just as intended. However now I want to add a check/uncheck all row. How do I programmatically toggle a switch within my custom rows?
I've tried creating the following function in rowFilter.js (and a similar one for toggle off):
exports.toggleOn = function() {
if ($.swtFilterStatus.value == false) {
$.swtFilterStatus.value = true;
swtFilterStatusChange();
}
};
And I've also tried this:
$.toggleOn = function() {
}
::EDIT:: Here is how I handle the check/uncheck all switch.
function allSwitch_Change(value) {
$.tblFilters.data[0].rows.forEach(function(row) {
if (value) {
row.toggleOn();
}
else {
row.toggleOf();
}
}
}
Then changing the Browse.js row above that does Alloy.createController with the following:
var newRow = require('rowFilter');
newRow.initialize(args);
But I just get an exception on the line with the require statement saying "Couldn't find module:rowFilter for architecture: x86_64".
What am I doing wrong and how do I implement a check/uncheck all row?

You can do something like this:
rowFilter.js
var args = arguments[0] || {};
var swtFilterStatusChange;
initialize();
function initialize() {
// Initialize filter row UI
$.lblItemHeader.text = args.title;
$.swtFilterStatus.value = args.value;
// Callback
swtFilterStatusChange = args.callback;
};
$.on('toggleOn',function(){
if ($.swtFilterStatus.value == false) {
$.swtFilterStatus.value = true;
swtFilterStatusChange();
}
});
browser.js
var args = { title: item.title, value: item.value, callback: swtFilterStatusChanged, };
var newRow = Alloy.createController('rowFilter', args);
newRow.trigger('toggleOn');
Other options to achieve your goal:
Global Events - Ti.App.addEventListener and Ti.App.fireEvent. Easy to implement, but has potential memory leak. Make sure to call Ti.App.removeEventListener after table row removed.
Get the switch view from the table row's children. Manually fire the event on it.
Store the reference to the callback swtFilterStatusChanged somewhere and call it later.

Related

jQuery plugin instances variable with event handlers

I am writing my first jQuery plugin which is a tree browser. It shall first show the top level elements and on click go deeper and show (depending on level) the children in a different way.
I got this up and running already. But now I want to implement a "back" functionality and for this I need to store an array of clicked elements for each instance of the tree browser (if multiple are on the page).
I know that I can put instance private variables with "this." in the plugin.
But if I assign an event handler of the onClick on a topic, how do I get this instance private variable? $(this) is referencing the clicked element at this moment.
Could please anyone give me an advise or a link to a tutorial how to get this done?
I only found tutorial for instance specific variables without event handlers involved.
Any help is appreciated.
Thanks in advance.
UPDATE: I cleaned out the huge code generation and kept the logical structure. This is my code:
(function ($) {
$.fn.myTreeBrowser = function (options) {
clickedElements = [];
var defaults = {
textColor: "#000",
backgroundColor: "#fff",
fontSize: "1em",
titleAttribute: "Title",
idAttribute: "Id",
parentIdAttribute: "ParentId",
levelAttribute: "Level",
treeData: {}
};
var opts = $.extend({}, $.fn.myTreeBrowser.defaults, options);
function getTreeData(id) {
if (opts.data) {
$.ajax(opts.data, { async: false, data: { Id: id } }).success(function (resultdata) {
opts.treeData = resultdata;
});
}
}
function onClick() {
var id = $(this).attr('data-id');
var parentContainer = getParentContainer($(this));
handleOnClick(parentContainer, id);
}
function handleOnClick(parentContainer, id) {
if (opts.onTopicClicked) {
opts.onTopicClicked(id);
}
clickedElements.push(id);
if (id) {
var clickedElement = $.grep(opts.treeData, function (n, i) { return n[opts.idAttribute] === id })[0];
switch (clickedElement[opts.levelAttribute]) {
case 1:
renderLevel2(parentContainer, clickedElement);
break;
case 3:
renderLevel3(parentContainer, clickedElement);
break;
default:
debug('invalid level element clicked');
}
} else {
renderTopLevel(parentContainer);
}
}
function getParentContainer(elem) {
return $(elem).parents('div.myBrowserContainer').parents()[0];
}
function onBackButtonClick() {
clickedElements.pop(); // remove actual element to get the one before
var lastClickedId = clickedElements.pop();
var parentContainer = getParentContainer($(this));
handleOnClick(parentContainer, lastClickedId);
}
function renderLevel2(parentContainer, selectedElement) {
$(parentContainer).html('');
var browsercontainer = $('<div>').addClass('myBrowserContainer').appendTo(parentContainer);
//... rendering the div ...
// for example like this with a onClick handler
var div = $('<div>').attr('data-id', element[opts.idAttribute]).addClass('fct-bs-col-md-4 pexSubtopic').on('click', onClick).appendTo(subtopicList);
// ... rendering the tree
var backButton = $('<button>').addClass('btn btn-default').text('Back').appendTo(browsercontainer);
backButton.on('click', onBackButtonClick);
}
function renderLevel3(parentContainer, selectedElement) {
$(parentContainer).html('');
var browsercontainer = $('<div>').addClass('myBrowserContainer').appendTo(parentContainer);
//... rendering the div ...
// for example like this with a onClick handler
var div = $('<div>').attr('data-id', element[opts.idAttribute]).addClass('fct-bs-col-md-4 pexSubtopic').on('click', onClick).appendTo(subtopicList);
// ... rendering the tree
var backButton = $('<button>').addClass('btn btn-default').text('Back').appendTo(browsercontainer);
backButton.on('click', onBackButtonClick);
}
function renderTopLevel(parentContainer) {
parentContainer.html('');
var browsercontainer = $('<div>').addClass('fct-page-pa fct-bs-container-fluid pexPAs myBrowserContainer').appendTo(parentContainer);
// rendering the top level display
}
getTreeData();
//top level rendering! Lower levels are rendered in event handlers.
$(this).each(function () {
renderTopLevel($(this));
});
return this;
};
// Private function for debugging.
function debug(debugText) {
if (window.console && window.console.log) {
window.console.log(debugText);
}
};
}(jQuery));
Just use one more class variable and pass this to it. Usually I call it self. So var self = this; in constructor of your plugin Class and you are good to go.
Object oriented way:
function YourPlugin(){
var self = this;
}
YourPlugin.prototype = {
constructor: YourPlugin,
clickHandler: function(){
// here the self works
}
}
Check this Fiddle
Or simple way of passing data to eventHandler:
$( "#foo" ).bind( "click", {
self: this
}, function( event ) {
alert( event.data.self);
});
You could use the jQuery proxy function:
$(yourElement).bind("click", $.proxy(this.yourFunction, this));
You can then use this in yourFunction as the this in your plugin.

Adding a custom context menu item to elFinder

I'm using elfinder and I would like to add new functionality by adding a command to the context menu. I found a solution on the github issue tracker of the project but I can't get it to work. Here's what I do:
var elf;
jQuery().ready(function() {
elFinder.prototype._options.commands.push('editimage');
elFinder.prototype._options.contextmenu.files.push('editimage');
elFinder.prototype.i18.en.messages['cmdeditimage'] = 'Edit Image';
elFinder.prototype.i18.de.messages['cmdeditimage'] = 'Bild bearbeiten';
elFinder.prototype.commands.editimage = function() {
this.exec = function(hashes) {
console.log('hallo');
}
}
elf = jQuery('#elfinder').elfinder({
...
//elfinder initialization
The context menu item does not show up, no error message is to be found in the console. I also tried putting editimage under contextmenu->"files" in the init part in case that was overwritten by the initialization.
I found the solution: The examples don't show the fact that you need to have a function called this.getstate inside of the elFinder.prototype.commands.yourcommand function. It shall return 0 when the icon is enabled and -1 when it's disabled.
So the full code for adding your own menu item or context menu item looks like this:
var elf;
jQuery().ready(function() {
elFinder.prototype.i18.en.messages['cmdeditimage'] = 'Edit Image';
elFinder.prototype.i18.de.messages['cmdeditimage'] = 'Bild bearbeiten';
elFinder.prototype._options.commands.push('editimage');
elFinder.prototype.commands.editimage = function() {
this.exec = function(hashes) {
//do whatever
}
this.getstate = function() {
//return 0 to enable, -1 to disable icon access
return 0;
}
}
...
elf = jQuery('#elfinder').elfinder({
lang: 'de', // language (OPTIONAL)
url : '/ext/elfinder-2.0-rc1/php/connector.php', //connector URL
width:'100%',
uiOptions : {
// toolbar configuration
toolbar : [
...
['quicklook', 'editimage'],
/*['copy', 'cut', 'paste'],*/
...
]},
contextmenu : {
...
// current directory file menu
files : [
'getfile', '|','open', 'quicklook', 'editimage', ...
]
}
}).elfinder('instance');
});
Hope this helps someone with the same problem.
Thanks for the answer, great!
One thing that wasn't clear was how the variables pass through.
So, for anyone else who finds this page....
elFinder.prototype.commands.editpres = function() {
this.exec = function(hashes) {
var file = this.files(hashes);
var hash = file[0].hash;
var fm = this.fm;
var url = fm.url(hash);
var scope = angular.element("body").scope();
scope.openEditorEdit(url);
}
// Getstate configured to only light up button if a file is selected.
this.getstate = function() {
var sel = this.files(sel),
cnt = sel.length;
return !this._disabled && cnt ? 0 : -1;
}
}
To get your icon to show up, add the following to your css file:
.elfinder-button-icon-editpres { background:url('../img/icons/editpres.png') no-repeat; }

Wait for all async functions to complete in jQuery

I'm filtering table using jQuery and all is well. This code works nicely:
$("*[id$='EquipmentTypeDropDownList']").change(filterTable);
$("*[id$='StateDropDownList']").change(filterTable);
function filterTable() {
var $equipmentDropDown = $("*[id$='EquipmentTypeDropDownList']");
var $stateDropDown = $("*[id$='StateDropDownList']");
var equipmentFilter = $equipmentDropDown.val();
var stateFilter = $stateDropDown.val();
$("tr.dataRow").each(function () {
var show = true;
var equimpent = $(this).find("td.equipment").text();
var state = $(this).find("td.readyState").text();
if (equipmentFilter != "Any" && equipmentFilter != equimpent) show = false;
if (stateFilter != "Any" && stateFilter != state) show = false;
if (show) {
$(this).fadeIn();
} else {
$(this).fadeOut();
}
});
$("table").promise().done(colorGridRows);
}
function colorGridRows() {
//for table row
$("tr:visible:even").css("background-color", "#DED7D1");
$("tr:visible:odd").css("background-color", "#EEEAE7");
}
colorGridRows function changes background color of even/odd rows for readability
Now, It would be nice if I can replace show/hide calls with fadeIn/fadeOut but I can't because coloring doesn't work (it runs before UI effect completed. If it was just one function parameter - I would just create function for completion and be done with it. But my table has many rows and loop runs through each. How do I wait for ALL to compelete?
EDITED: Code sample updated showing how I try to use promise() but it doesn't work. It fires but I don't get odd/even coloring.
Use the promise object for animations.
$("*[id$='StateDropDownList']").change(function () {
var filtervar = $(this).val();
$('tr td.readyState').each(function () {
if (filtervar == "Any" || $(this).text() == filtervar) {
$(this).parent().fadeIn();
} else {
$(this).parent().fadeOut();
}
}).parent().promise().done(colorGridRows);
//colorGridRows();
});

Is it possible to reinitialize a CKEditor Combobox/Drop Down Menu?

How do I dynamically update the items in a drop down?
I have a custom plugin for CKEditor that populates a drop down menu with a list of items which I can inject into my textarea.
This list of items comes from a Javascript array called maptags, which is updated dynamically for each page.
var maptags = []
This list of tags gets added to the drop down when you first click on it by the init: function. My problem is what if the items in that array change as the client changes things on the page, how can I reload that list to the updated array?
Here is my CKEditor Plugin code:
CKEDITOR.plugins.add('mapitems', {
requires: ['richcombo'], //, 'styles' ],
init: function (editor) {
var config = editor.config,
lang = editor.lang.format;
editor.ui.addRichCombo('mapitems',
{
label: "Map Items",
title: "Map Items",
voiceLabel: "Map Items",
className: 'cke_format',
multiSelect: false,
panel:
{
css: [config.contentsCss, CKEDITOR.getUrl(editor.skinPath + 'editor.css')],
voiceLabel: lang.panelVoiceLabel
},
init: function () {
this.startGroup("Map Items");
//this.add('value', 'drop_text', 'drop_label');
for (var this_tag in maptags) {
this.add(maptags[this_tag][0], maptags[this_tag][1], maptags[this_tag][2]);
}
},
onClick: function (value) {
editor.focus();
editor.fire('saveSnapshot');
editor.insertHtml(value);
editor.fire('saveSnapshot');
}
});
}
});
I think I just solved this actually.
Change your init like this:
init: function () {
var rebuildList = CKEDITOR.tools.bind(buildList, this);
rebuildList();
$(editor).bind('rebuildList', rebuildList);
},
And define the buildList function outside that scope.
var buildListHasRunOnce = 0;
var buildList = function () {
if (buildListHasRunOnce) {
// Remove the old unordered list from the dom.
// This is just to cleanup the old list within the iframe
$(this._.panel._.iframe.$).contents().find("ul").remove();
// reset list
this._.items = {};
this._.list._.items = {};
}
for (var i in yourListOfItems) {
var item = yourListOfItems[i];
// do your add calls
this.add(item.id, 'something here as html', item.text);
}
if (buildListHasRunOnce) {
// Force CKEditor to commit the html it generates through this.add
this._.committed = 0; // We have to set to false in order to trigger a complete commit()
this.commit();
}
buildListHasRunOnce = 1;
};
The clever thing about the CKEDITOR.tools.bind function is that we supply "this" when we bind it, so whenever the rebuildList is triggered, this refer to the richcombo object itself which I was not able to get any other way.
Hope this helps, it works fine for me!
ElChe
I could not find any helpful documenatation around richcombo, i took a look to the source code and got an idea of the events i needed.
#El Che solution helped me to get through this issue but i had another approach to the problem because i had a more complex combobox structure (search,groups)
var _this = this;
populateCombo.call(_this, data);
function populateCombo(data) {
/* I have a search workaround added here */
this.startGroup('Default'); /* create default group */
/* add items with your logic */
for (var i = 0; i < data.length; i++) {
var dataitem = data[i];
this.add(dataitem.name, dataitem.description, dataitem.name);
}
/* other groups .... */
}
var buildListHasRunOnce = 0;
/* triggered when combo is shown */
editor.on("panelShow", function(){
if (buildListHasRunOnce) {
// reset list
populateCombo.call(_this, data);
}
buildListHasRunOnce = 1;
});
/* triggered when combo is hidden */
editor.on("panelHide", function(){
$(_this._.list.element.$).empty();
_this._.items = {};
_this._.list._.items = {};
});
NOTE
All above code is inside addRichCombo init callback
I remove combobox content on "panelHide" event
I repopulate combobox on "panelShow" event
Hope this helps

making certain cells of an ExtJS GridPanel un-editable

I currently have a GridPanel with the Ext.ux.RowEditor plugin. Four fields exist in the row editor: port, ip address, subnet and DHCP. If the DHCP field (checkbox) of the selected row is checked, I need to make the other three fields un-editable.
I've been trying to perform this code when the beforeedit event is triggered, but to no avail... I've only found ways to make the entire column un-editable. My code so far:
this.rowEditor.on({
scope: this,
beforeedit: this.checkIfEditable
});
checkIfEditable:function(rowEditor, rowIndex) {
if(this.getStore().getAt(rowIndex).get('dhcp')) {
// this function makes the entire column un-editable:
this.getColumnModel().setEditable(2, false);
// I want to make only the other three fields of the current row
// uneditable.
}
}
Please let me know if any clarification is needed.
Any help potentially extending RowEditor to accomplish the target functionality would be greatly appreciated as well!
You can add into RowEditor.js within the function startEditing the call to the function isCellEditable
//.... RowEditor.js
startEditing: function(rowIndex, doFocus){
//.... search for the starting of the below loop into the source code
var cm = g.getColumnModel(), fields = this.items.items, f, val;
for(var i = 0, len = cm.getColumnCount(); i < len; i++){
val = this.preEditValue(record, cm.getDataIndex(i));
f = fields[i];
f.setValue(val);
// *** here add a call to isCellEditable *** //
f.setDisabled(!cm.isCellEditable(i, rowIndex));
// ***************************************** //
this.values[f.id] = Ext.isEmpty(val) ? '' : val;
}
//....
Then override the isCellEditable of your column model and disabled the field based on you condition:
YYY.getColumnModel().isCellEditable = function(colIndex, rowIndex){
if (grid.getStore().getAt(rowIndex).get('dhcp')) {
// you can do more check base on colIndex
// only to disabled the one you want
return false;
}
return Ext.grid.ColumnModel.prototype.isCellEditable.call(this, colIndex, rowIndex);
}
As the docs state:
If the listener returns false
the editor will not be activated.
So...
this.rowEditor.on({
scope: this,
beforeedit: this.checkIfEditable
});
checkIfEditable:function(rowEditor, rowIndex) {
if(this.getStore().getAt(rowIndex).get('dhcp')) {
return false;
}
}
Simply returning false will be enough to cancel the editing ability.
Gotcha.
Interesting idea - a bit of a hassle to implement, but possible.
You need to approach this from two directions:
1 ) edit starts
2 ) checkbox is checked/unchecked
For the first part, I think you could use almost the same code I have above, remove the 'return false' and use the reference to the rowEditor to loop through the items collection, disabling (call the disable method on them) the fields that are not your checkbox field.
The second part of this is to add a handler to the checkbox which would do the same thing.
The following works to make a specific cell uneditable (add the event to the roweditor):
beforeedit: function (roweditor, rowIndex) {
var data = roweditor.grid.store.getAt(rowIndex).data;
var cm = roweditor.grid.getColumnModel();
// disable the first column (can not be edited)
if (** make your check here ***) {
var c = cm.getColumnAt(0);
c.editor.disable();
}
roweditor.initFields();
}
As of ExtJS 3.4 you can just override isCellEditable, as in the example here:
http://docs.sencha.com/ext-js/3-4/#!/api/Ext.grid.ColumnModel-method-isCellEditable
Here's the simpler version :
http://jsfiddle.net/snehalmasne/8twwywcp/
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 1
,pluginId: 'editing'
})
]
Provide the condition below for the cells to make the un-editable :
grid.on('beforeedit', function(editor, e) {
if (e.record.get('phone') == '555-111-1224')
return false;
});
just set the column in your columnModel/columns to editable:false for fields that should not be editable.
columns: [
{ header: "Ticker", width: 60, editable:false },
{ header: "Company Name", width: 150, id: 'company'},
{ header: "Market Cap."},
{ header: "$ Sales", renderer: money},
{ header: "Employees", resizable: false}
]
I ran into the same problem. Rather than using the GridPanel with the Ext.ux.RowEditor plugin, I used the Ext.grid.EditorGridPanel. In this case, you can specify the editor for each of the other three fields (port, ip address, and subnet) in the column model with a beforeshow event handler as follows:
editor: new Ext.form.TextArea({
height:80,
allowBlank: false,
listeners:{
beforeshow: function(column) {
if (column.gridEditor.record.get('dhcp')) {
column.gridEditor.cancelEdit();
}
}
}
})
Ha!
I made a dirty one, I added an event this.fireEvent('starting', this, fields,record); AT THE END of startEditing
startEditing: function(rowIndex, doFocus){
if(this.editing && this.isDirty()){
this.showTooltip(this.commitChangesText);
return;
}
if(Ext.isObject(rowIndex)){
rowIndex = this.grid.getStore().indexOf(rowIndex);
}
if(this.fireEvent('beforeedit', this, rowIndex) !== false){
this.editing = true;
var g = this.grid, view = g.getView(),
row = view.getRow(rowIndex),
record = g.store.getAt(rowIndex);
this.record = record;
this.rowIndex = rowIndex;
this.values = {};
if(!this.rendered){
this.render(view.getEditorParent());
}
var w = Ext.fly(row).getWidth();
this.setSize(w);
if(!this.initialized){
this.initFields();
}
var cm = g.getColumnModel(), fields = this.items.items, f, val;
for(var i = 0, len = cm.getColumnCount(); i < len; i++){
val = this.preEditValue(record, cm.getDataIndex(i));
f = fields[i];
f.setValue(val);
this.values[f.id] = Ext.isEmpty(val) ? '' : val;
}
this.verifyLayout(true);
if(!this.isVisible()){
this.setPagePosition(Ext.fly(row).getXY());
} else{
this.el.setXY(Ext.fly(row).getXY(), {duration:0.15});
}
if(!this.isVisible()){
this.show().doLayout();
}
if(doFocus !== false){
this.doFocus.defer(this.focusDelay, this);
}
/*I ADDED THIS EVENT ---- contains the fields and record
*/
this.fireEvent('starting', this, fields,record);
}
}
THEN
var editor = new Ext.ux.grid.RowEditor({
saveText: 'Update',
listeners : {
'starting' : function(rowEditor, fields, record){
if(!record.data.equipo_id){
fields[4].setDisabled(false);
}else{
fields[4].setDisabled(true);
}
},
Using Ext JS 4 and the RowEditing plugin i managed to achieve this using something like
rowEditor.on('beforeedit', function (context) {
this.editor.query('textfield')[0].setDisabled(/* your condition here */);
});
the record data is available through context.record.data

Categories

Resources