Why aren't these two functions toggling on click event? - toggle

I'm trying to toggle two functions. When user clicks the pause button, the input fields are disabled, the label is text is changed to grey and the button changes to a different image. I thought I could use .toggle(), but I can't get the two functions to work either -- only the first one function runs (pauseEmailChannel();), not both on toggle click. I found the even/odd clicks detection script here on SO, but that is not "toggling" these two functions on the click event. My code may be ugly code, but I'm still learning and wanted to show how I am thinking -- right or wrong. At any rate, can someone give me a solution to how to do this? I didn't think it would be too difficult but I'm stuck. Thanks.
HTML
jQuery
$(".btn_pause").click(function(){
var count = 0;
count++;
//even odd click detect
var isEven = function(num) {
return (num % 2 === 0) ? true : false;
};
// on odd clicks do this
if (isEven(count) === false) {
pauseEmailChannel();
}
// on even clicks do this
else if (isEven(count) === true) {
restoreEmailChannel();
}
});
// when user clicks pause button - gray out/disable
function pauseEmailChannel(){
$("#channel-email").css("color", "#b1b1b1");
$("#notify-via-email").attr("disabled", true);
$("#pause-email").removeClass("btn_pause").addClass("btn_disable-pause");
}
// when user clicks cancel button - restore default
function restoreEmailChannel(){
$("#channel-email").css("color", "#000000");
$("#notify-email").attr("disabled", false);
$("#pause-email").removeClass("disable-pause").addClass("btn_pause");
$("input[value='email']").removeClass("btn_disable-remove").addClass("btn_remove");
}

try this code. It should work fine, except that I could make a mistake when it is even and when odd, but that should be easy to fix.
$(".btn_pause").click(function(){
var oddClick = $(this).data("oddClick");
$(this).data("oddClick", !oddClick);
if(oddClick) {
pauseEmailChannel();
}
else {
restoreEmailChannel();
}
});

The count variable is initialized and set to 0 every time .btn_pause is clicked. You need to move the variable to a higher scope.
For example,
$(".btn_pause").each(function(){
var count = 0;
$(this).click(function(){
count++;
...
});
});
In this way count is initialized only once and it is accessible in the click event handler.
As an alternative way you can also use:
$(".btn_pause").each(function(){
var count = 0;
$(this).click(function(){
[restoreEmailChannel, pauseEmailChannel][count = 1 - count]();
});
});
If the previous construct was too abstract, a more verbose one will look like this:
$(".btn_pause").each(function(){
/* Current element in the array to be executed */
var count = 0;
/* An array with references to Functions */
var fn = [pauseEmailChannel, restoreEmailChannel];
$(this).click(function(){
/* Get Function from the array and execute it */
fn[count]();
/* Calculate next array element to be executed.
* Notice this expression will make "count" loop between the values 0 and 1.
*/
count = 1 - count;
});
});

Related

RxJs Observable with infinite scroll OR how to combine Observables

I have a table which uses infinite scroll to load more results and append them, when the user reaches the bottom of the page.
At the moment I have the following code:
var currentPage = 0;
var tableContent = Rx.Observable.empty();
function getHTTPDataPageObservable(pageNumber) {
return Rx.Observable.fromPromise($http(...));
}
function init() {
reset();
}
function reset() {
currentPage = 0;
tableContent = Rx.Observable.empty();
appendNextPage();
}
function appendNextPage() {
if(currentPage == 0) {
tableContent = getHTTPDataPageObservable(++currentPage)
.map(function(page) { return page.content; });
} else {
tableContent = tableContent.combineLatest(
getHTTPDataPageObservable(++currentPage)
.map(function(page) { return page.content; }),
function(o1, o2) {
return o1.concat(o2);
}
)
}
}
There's one major problem:
Everytime appendNextPage is called, I get a completely new Observable which then triggers all prior HTTP calls again and again.
A minor problem is, that this code is ugly and it looks like it's too much for such a simple use case.
Questions:
How to solve this problem in a nice way?
Is is possible to combine those Observables in a different way, without triggering the whole stack again and again?
You didn't include it but I'll assume that you have some way of detecting when the user reaches the bottom of the page. An event that you can use to trigger new loads. For the sake of this answer I'll say that you have defined it somewhere as:
const nextPage = fromEvent(page, 'nextpage');
What you really want to be doing is trying to map this to a stream of one directional flow rather than sort of using the stream as a mutable object. Thus:
const pageStream = nextPage.pipe(
//Always trigger the first page to load
startWith(0),
//Load these pages asynchronously, but keep them in order
concatMap(
(_, pageNum) => from($http(...)).pipe(pluck('content'))
),
//One option of how to join the pages together
scan((pages, p) => ([...pages, p]), [])
)
;
If you need reset functionality I would suggest that you also consider wrapping that whole stream to trigger the reset.
resetPages.pipe(
// Used for the "first" reset when the page first loads
startWith(0),
//Anytime there is a reset, restart the internal stream.
switchMapTo(
nextPage.pipe(
startWith(0),
concatMap(
(_, pageNum) => from($http(...)).pipe(pluck('content'))
),
scan((pages, p) => ([...pages, p]), [])
)
).subscribe(x => /*Render page content*/);
As you can see, by refactoring to nest the logic into streams we can remove the global state that was floating around before
You can use Subject and separate the problem you are solving into 2 observables. One is for scrolling events , and the other is for retrieving data. For example:
let scrollingSubject = new Rx.Subject();
let dataSubject = new Rx.Subject();
//store the data that has been received back from server to check if a page has been
// received previously
let dataList = [];
scrollingSubject.subscribe(function(page) {
dataSubject.onNext({
pageNumber: page,
pageData: [page + 10] // the data from the server
});
});
dataSubject.subscribe(function(data) {
console.log('Received data for page ' + data.pageNumber);
dataList.push(data);
});
//scroll to page 1
scrollingSubject.onNext(1);
//scroll to page 2
scrollingSubject.onNext(2);
//scroll to page 3
scrollingSubject.onNext(3);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.js"></script>

With SoundCloud default audio widget can you set it to shuffle from JavaScript?

I am using the default SoundCloud audio widget to play a playlist and would like the songs to play in a random order. I am using the SoundCloud JavaScript SDK oEmbed object (the iframe version).
<script src="//connect.soundcloud.com/sdk.js"></script>
SC.oEmbed("//soundcloud.com/buzzinfly", {
auto_play: true,
start_track: random_start_track,
iframe: true,
maxwidth: 480,
enable_api: true,
randomize: true
},
document.getElementById("soundcloud_player"));
The documentation doesn't mention any randomize or shuffle attribute, but other undocumented attributes like start_track are supported with oembed.
//developers.soundcloud.com/docs/oembed#parameters
//developers.soundcloud.com/docs/widget
Does any one know if there is an attribute to shuffle the song order in the default audio widget?
If not, is there is a way to capture events from the default SoundCloud widget, so I can play a random song after a song finish event? Like you can with the custom player.
//developers.soundcloud.com/docs/custom-player#events
$(document).bind('onPlayerTrackSwitch.scPlayer', function(event, track){
// goto random track
});
Thanks
Update
Here is code am I using after getting gryzzly's help.
The next button works great. I can skip thru random songs. Unfortunately, when a track finishes playing, I hear the audio of two songs: the next song in the playlist and the random track that is skipped to in the FINISH event.
var widget = null;
var song_indexes = new Array();
var current_index = 0;
$(function() {
var iframe = document.querySelector('#soundcloud_player iframe');
widget = SC.Widget(iframe);
widget.bind(SC.Widget.Events.READY, function() {
widget.unbind(SC.Widget.Events.FINISH);
widget.bind(SC.Widget.Events.FINISH, function() {
play_next_shuffled_song();
});
widget.getSounds(function(sounds) {
create_shuffled_indexes(sounds.length);
play_next_shuffled_song();
});
});
$("#button_sc_next").on("click", play_next_shuffled_song);
});
function play_next_shuffled_song() {
current_index++;
if (current_index >= song_indexes.length) {
current_index = 0;
}
var track_number = song_indexes[current_index];
widget.skip(track_number);
}
function create_shuffled_indexes (num_songs) {
for (var i=0;i<num_songs;i++) {
song_indexes.push(i);
}
song_indexes = shuffle(song_indexes);
}
//+ Jonas Raoni Soares Silva
//# http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o){ //v1.0
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
You can find the documentation for Widget API here.
Pseudo code for this would be something like:
load widget
get widget sounds LENGTH /* say 5 */
create an ARRAY of that LENGTH and shuffle it /* to have something like [3, 1, 0, 2, 4] */
create function SKIP that will check if ARRAY still has any items in it (length is not 0) and skip player to array.pop() index /* pop will return the last item in the array and return its value */
attach event handler to FINISH events that will run SKIP function
run SKIP function first time yourself
If user skips with the “next” control in widget's UI the widget will
just play next song in the list. You could perhaps detect that
somehow and skip to another random track.
I hope this helps!

GTK+ How do I find which radio button is selected?

The tutorial here http://developer.gnome.org/gtk-tutorial/2.90/x542.html
shows how to set up the radio buttons, but neglects to tell you how to use them.
How do I then find which radio button is selected?
My solution:
Initialise radio buttons with:
rbutton1 = gtk_radio_button_new_with_label(NULL, "button1");
gtk_box_pack_start(GTK_BOX(rbutton_box), rbutton1, TRUE, TRUE, 0);
rbuttonGroup = gtk_radio_button_get_group(GTK_RADIO_BUTTON(rbutton1)); /*not sure what I'd use this line for currently though*/
rbutton2 = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(rbutton1), "button 2");
gtk_box_pack_start(GTK_BOX(rbutton_box), rbutton2, TRUE, TRUE, 0);
rbutton3 = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(rbutton1), "button 3");
gtk_box_pack_start(GTK_BOX(rbutton_box), rbutton3, TRUE, TRUE, 0);
And update a variable telling you which radio button is selected with this method:
void checkRadioButtons()
{
if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(rbutton1))==TRUE) selectedRadioButton =1;
if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(rbutton2))==TRUE) selectedRadioButton =2;
if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(rbutton3))==TRUE) selectedRadioButton =3;
}
Google brought me here for python / pygtk / pygtk3 searches, so I hope its okay that I post a pygtk solution:
def _resolve_radio(self, master_radio):
active = next((
radio for radio in
master_radio.get_group()
if radio.get_active()
))
return active
This uses a generator to return the first (which should be the only) active radio box that is active.
This is how I do it.
GtkRadioButton * radio_button;
GtkRadioButton * radio_button1;
GtkRadioButton * radio_button2;
...
GSList * tmp_list = gtk_radio_button_get_group (radio_button);//Get the group of them.
GtkToggleButton *tmp_button = NULL;//Create a temp toggle button.
while (tmp_list)//As long as we didn't reach the end of the group.
{
tmp_button = tmp_list->data;//Get one of the buttons in the group.
tmp_list = tmp_list->next;//Next time we're going to check this one.
if (gtk_toggle_button_get_active(tmp_button))//Is this the one active?
break;//Yes.
tmp_button = NULL;//We've enumerated all of them, and none of them is active.
}
//Here. tmp_button holds the active one. NULL if none of them is active.
See the discussion here.
I don't know if they will add this function into it (seems not).
Here's how I suggest doing it:
void radio_button_selected (GtkWidget *widget, gpointer data)
{
if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget))
{
GSLIST *group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (widget));
g_print ("Index = %i%\n", g_slist_index (group, widget));
}
}
You may connect to the GtkToggleButton::toggled signal instead. In the associated callback, you'll be able to update your variable. As for the call to gtk_radio_button_get_group, you only need it if you call gtk_radio_button_new_with_label instead of gtk_radio_button_new_with_label_with_widget, as specified in the tutorial you're refering to.
Let's create a serie of buttons :
for severity in levels:
radio = gtk.RadioButton(group=radioButtons, label=severity)
if severity == actualLevel:
radio.set_active(True)
hBox.pack_start(radio, True, True, 3)
radio.connect('toggled', self.radioButtonSelected, severity)
and all buttons are connected to the same handler :
def radioButtonSelected(self, button, currentSeverity):
# proceed with the task
# as you can see, button is passed by as argument by the event handler
# and you can, for example, get the button label :
labelReadFromButton = button.getLabel()
Use lambda expressions if you dont want to mess around with the annoying methods, still have to use connect though, but its alot easier to read:
Enum RadioValues { A, B, C, none };
RadioValues values = RadioValues.none; // only needed if you dont have an initially selected radio button
MyConstructor()
{
Build();
// asumming you have 3 radio buttons: radioA, radioB, radioC:
radioA.Toggled += (sender,e) => values = RadioValues.A;
radioB.Toggled += (sender,e) => values = RadioValues.B;
radioC.Toggled += (sender,e) => values = RadioValues.C;
}
and thats it, no methods to deal with, and you dont have to restrict yourself to just that either, you can also use an anonymous function if you need more flex--of course the next step after that is using methods. Unfortunately they didnt offer a simple .Checked property, my next suggestion is to override the radio button itself and chain a Checked property when it's toggled state is changed, emulating other frameworks like MFC, Qt, and Winforms... etc.
PS: I left out boilerplate code for simplicity's sake, which can make answers a bit more muddled and you probably just want the facts not a demonstration on whether or not I can properly call a constructor :)
My solution for GTKmm is quite easier,
You just have to call the function :
my_radio_button.get_active(); \n
This will return either 0 if its unactive or 1 if its active.
This is a demo code using Radio Buttons, where you can find how I find which radio button is selected:
#include <gtkmm/window.h>
#include <gtkmm/box.h>
#include <gtkmm/radiobutton.h>
#include <gtkmm/separator.h>
#include <gtkmm/application.h>
#include <iostream>
class ButtonWindow : public Gtk::Window
{
private:
//Child widgets:
Gtk::Box m_Box_Top, m_Box1, m_Box2;
Gtk::RadioButton m_RadioButton1, m_RadioButton2, m_RadioButton3;
Gtk::Separator m_Separator;
Gtk::Button m_Button_Close;
Gtk::RadioButton *m_SelectedButton{nullptr};
public:
ButtonWindow()
: m_Box_Top(Gtk::ORIENTATION_VERTICAL),
m_Box1(Gtk::ORIENTATION_VERTICAL, 15),
m_Box2(Gtk::ORIENTATION_VERTICAL, 0),
m_RadioButton1("button 1"),
m_RadioButton2("button 2"),
m_RadioButton3("button 3"),
m_Button_Close("close")
{
// Set title and border of the window
set_title("radio buttons");
set_border_width(0);
// Put radio buttons 2 and 3 in the same group as 1:
m_RadioButton2.join_group(m_RadioButton1);
m_RadioButton3.join_group(m_RadioButton1);
// Add outer box to the window (because the window
// can only contain a single widget)
add(m_Box_Top);
//Put the inner boxes and the separator in the outer box:
m_Box_Top.pack_start(m_Box1);
m_Box_Top.pack_start(m_Separator);
m_Box_Top.pack_start(m_Box2);
// Set the inner boxes' borders
m_Box1.set_border_width(20);
m_Box2.set_border_width(10);
// Put the radio buttons in Box1:
m_Box1.pack_start(m_RadioButton1);
m_Box1.pack_start(m_RadioButton2);
m_Box1.pack_start(m_RadioButton3);
// Put Close button in Box2:
m_Box2.pack_start(m_Button_Close);
// Connect the button signals:
#if 1 // Full C++11: (change this to #if 0 to use the traditional way)
m_RadioButton1.signal_clicked().connect([&]{on_radio_button_clicked(m_RadioButton1);});
m_RadioButton2.signal_clicked().connect([&]{on_radio_button_clicked(m_RadioButton2);});
m_RadioButton3.signal_clicked().connect([&]{on_radio_button_clicked(m_RadioButton3);});
m_Button_Close.signal_clicked().connect([&]{on_close_button_clicked();});
#else // Traditional:
m_RadioButton1.signal_clicked() // Full sigc
.connect(sigc::bind(sigc::mem_fun(*this, &ButtonWindow::on_radio_button_clicked),
sigc::ref(m_RadioButton1)));
m_RadioButton2.signal_clicked() // sigc && C++98
.connect(std::bind(sigc::mem_fun(*this, &ButtonWindow::on_radio_button_clicked),
std::ref(m_RadioButton2)));
m_RadioButton3.signal_clicked() // Full C++98
.connect(std::bind(&ButtonWindow::on_radio_button_clicked, this,
std::ref(m_RadioButton3)));
m_Button_Close.signal_clicked()
.connect(sigc::mem_fun(*this, &ButtonWindow::on_close_button_clicked));
#endif
// Set the second button active:
m_RadioButton2.set_active();
// Make the close button the default widget:
m_Button_Close.set_can_default();
m_Button_Close.grab_default();
// Show all children of the window:
show_all_children();
}
protected:
//Signal handlers:
void on_radio_button_clicked(Gtk::RadioButton& button)
{
if(m_SelectedButton != &button && button.get_active())
{
m_SelectedButton = &button;
std::cout << "Radio "<< m_SelectedButton->get_label() << " selected.\n";
}
}
void on_close_button_clicked()
{
hide(); // Close the application
}
};
int main(int argc, char *argv[])
{
auto app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ButtonWindow button;
//Shows the window and returns when it is closed.
return app->run(button);
}

Add ondblClick and click event to Codemirror

I would like to add onDblClick event to codemirror 2. I found that onCursorActivity does not deliverer the event so there is no way for me from this method to filter the events.
How can I implement onDbClick event on Codemirror ?
Thanks in advance.
You can call on method on object returned by CodeMirror:
var cm = CodeMirror.fromTextArea(document.querySelector('textarea'));
cm.on('dblclick', function() {
alert('You double click the editor');
});
You can find the list of all available events in documentation.
Register a handler on the element returned by the getWrapperElement() method. Unless you want to not just detect double-clicks, but also prevent the default (select word under mouse cursor) from occurring... in that case I guess some modification of the core code is needed.
http://jsfiddle.net/yusafkhaliq/NZF53/1/
Since codemirror renders inside the element specified you can add an ondblclick event to the element, like below the highlighter renders without line numbers once double clicked that specific elements will display line numbers
var codeelems = document.getElementsByClassName("code");
for (i = 0; i < codeelems.length; i++) {
(function ($this) {
var value = $this.innerHTML;
$this.innerHTML = "";
var editor = CodeMirror($this, {
value: value,
mode: "text/javascript",
lineNumbers: false
});
$this.ondblclick = function () {
editor.setOption("lineNumbers", true);
}
})(codeelems[i]);
}

What is the proper way in OpenLayers (OSM) to trigger a popup for a feature?

I have the feature ID, I can grab the marker layer on GeoRSS loadend, but I'm still not sure how to cause the popup to appear programmatically.
I'll create the popup on demand if that's necessary, but it seems as though I should be able to get the id of the marker as drawn on the map and call some event on that. I've tried using jQuery and calling the $(marker-id).click() event on the map elements, but that doesn't seem to be working. What am I missing?
Since I was asked for code, and since I presumed it to be boilerplate, here's where I am so far:
map = new OpenLayers.Map('myMap');
map.addLayer(new OpenLayers.Layer.OSM());
map.addLayer(new OpenLayers.Layer.GeoRSS(name,url));
//I've done some stuff as well in re: projections and centering and
//setting extents, but those really don't pertain to this question.
Elsewhere I've done a bit of jQuery templating and built me a nice list of all the points that are being shown on the map. I know how to do a callback from the layer loadend and get the layer object, I know how to retrieve my layer out of the map manually, I know how to iter over the layers collection and find my layer. So I can grab any of those details about the popup, but I still don't know how to go about using the built-in methods of the DOM or of this API to make it as easy as element.click() which is what I would prefer to do.
You don't have to click the feature to open a popup.
First you need a reference to the feature from the feature id. I would do that in the loadend event of the GeoRSS layer, using the markers property on the layer.
Assuming you have a reference to your feature, I would write a method which handles the automatic popup:
var popups = {}; // to be able to handle them later
function addPopup(feature) {
var text = getHtmlContent(feature); // handle the content in a separate function.
var popupId = evt.xy.x + "," + evt.xy.y;
var popup = popups[popupId];
if (!popup || !popup.map) {
popup = new OpenLayers.Popup.Anchored(
popupId,
feature.lonlat,
null,
" ",
null,
true,
function(evt) {
delete popups[this.id];
this.hide();
OpenLayers.Event.stop(evt);
}
);
popup.autoSize = true;
popup.useInlineStyles = false;
popups[popupId] = popup;
feature.layer.map.addPopup(popup, true);
}
popup.setContentHTML(popup.contentHTML + text);
popup.show();
}
fwiw I finally came back to this and did something entirely different, but his answer was a good one.
//I have a list of boxes that contain the information on the map (think google maps)
$('.paginatedItem').live('mouseenter', onFeatureSelected).live('mouseleave',onFeatureUnselected);
function onFeatureSelected(event) {
// I stuff the lookup attribute (I'm lazy) into a global
// a global, because there can be only one
hoveredItem = $(this).attr('lookup');
/* Do something here to indicate the onhover */
// find the layer pagination id
var feature = findFeatureById(hoveredItem);
if (feature) {
// use the pagination id to find the event, and then trigger the click for that event to show the popup
// also, pass a null event, since we don't necessarily have one.
feature.marker.events.listeners.click[0].func.call(feature, event)
}
}
function onFeatureUnselected(event) {
/* Do something here to indicate the onhover */
// find the layer pagination id
var feature = findFeatureById(hoveredItem);
if (feature) {
// use the pagination id to find the event, and then trigger the click for that event to show the popup
// also, pass a null event, since we don't necessarily have one.
feature.marker.events.listeners.click[0].func.call(feature, event)
}
/* Do something here to stop the indication of the onhover */
hoveredItem = null;
}
function findFeatureById(featureId) {
for (var key in map.layers) {
var layer = map.layers[key];
if (layer.hasOwnProperty('features')) {
for (var key1 in layer.features) {
var feature = layer.features[key1];
if (feature.hasOwnProperty('id') && feature.id == featureId) {
return feature;
}
}
}
}
return null;
}
also note that I keep map as a global so I don't have to reacquire it everytime I want to use it