Pass function to alertify.js - javascript

Im knocking my head to this scripts and I cant get my function to be displayed inside the Aletify.js alerts.
Some help will be incredibly helpful ;-)
The Function:
Oshoplang = {
// System Message Text
RemoveError: '<p>This item has now been removed from your cart.\n\nThank you.',
Added: 'Has now been added to your cart',
OutOfStock: '<p>This item is not currently available or is out of stock.</p>',
PreOrder: '<p>Your pre-order has been made successfully.\n\nThank you.</p>',
InvalidQuantity: '<p>It looks like you entered an invalid quantity.\n\nPlease try again.</p>',
}
window.alert = function() {};
$("#confirm-else").on('click', function() {
reset();
$('#e-content').addClass('blur');
alertify.alert(Oshoplang, function(e) {
if (e) {
alertify.success("OK");
$('#e-content').removeClass('blur');
location.reload();
} else {
alertify.error("You've clicked Cancel");
}
});
return false;
});
I normally don't get a message on the run, but this way but i believe i'm close somewhere :-)

Not sure if you're still having this issue, but I believe that the alertify.alert function doesn't have any callbacks, as it's just a way to show a message. You're probably looking for the alertify.confirm instead.
The message is also not showing up because the first argument to alertify.alert or alertify.confirm needs to be a string. In your example, you're passing an object.
I've set up a demo of your code which has been adjusted to work on here on JSFiddle.
For what it's worth, the code sample is using an older version of alertify (0.3) and it has been updated, so that version 1 which is now out would have a somewhat adjusted syntax.

Related

SessionStorage Navigation

Greets, so I I'm trying to learn jquery/javascript storage and ran into an issue where I am building a navigation that should remember and place you where you last were if you refresh the page (that's why i use sessionStorage rather then localStorage).
But I can't seem to change the sessionStorage variable to the new location, nor figure out a functional way to get the user back on refreshing the page.
This is what I currently have.
$(function() {
sessionStorage.setItem('position', '.first');
var location = sessionStorage.getItem('position');
$('li', this).click(function() {
cls = $(this).text();
if('.' + cls != location) {
$(location).slideToggle(400);
$('.' + cls).delay(400).slideToggle(400);
sessionStorage.setItem('position', '.' + cls)
console.log(location)
};
});
});
https://jsfiddle.net/Unkn0wn96/ndj9sqpe/
The code works in an very odd way, rather then how it's intended, including never changing the value when I console.log(location).
I made some further testing on this and found a 'more' working way in the was that the sessionStorage does change to something, yet it not being usefull.
https://jsfiddle.net/Unkn0wn96/nkbtykkr/
but yet, they elements don't toggle as they should, including that when I console log sessionStorage.position it returns NaN. Also for some odd reason I can't store sessionStorage.position within a variable, it just refuses to change its value. I have no clue why this is happening.
So I was finally able to solve my issue with sessionStorage, since there was not much of help I'd assume the information regarding the case was limited and so wish to share my solution. All thought it does not work fully as intended it does execute it's main function.
$(function() {
$('button').on('click', function() {
var msg = '.'+$(this).text();
localStorage.setItem('color', 'blue') //Default (does not matter since the if statement does not register)
if(msg != '.' + localStorage.color) { // DOES NOT REGISTER
if(localStorage.length > 0) {
localStorage.removeItem('color')
console.log('localStorage.length : ' + localStorage.length)
};
localStorage.setItem('color', msg)
console.log(localStorage.color)
} else {
console.log('cancelled')
}
});
});
https://jsfiddle.net/mdqjoz69/4/
So what I finally was able to achieve was to make a localStorage key change it's value regarding of what button you press.
What I failed to achieve was being able to check the stored data to not execute whenever you store something that have already been stored. There might be a work around for this. But since the code serves its main purpose I'll let it slide.

ExtJS 3.4 MessageBox buttons YESNO strange behaviour

I have this problem with MessageBox component in ExtJS 3.4 and I'm searching desperately for a solution.
function supprimerCatalogPreEnregFunction() {
Ext.Msg.show({
msg: document.getElementById('confirmDeleteMessage').value,
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.ERROR,
fn : function (btn) {
if (btn == 'yes') {
document.getElementById('deleteForm:deleteCatalogPreEnreg').onclick();
}
}
});
}
The problem is that my btn return value 1, not 'yes' or 'no' as i expect. And it drives me crazy because I've trying a lot of solutions and I can't understand why this happens.
This function is a handler for a new Ext.Button.
The button is part of a new Ext.Panel, buttons:[...].
I can't understand why the button has that strange value and it frustrates me a lot.
Can a missing comma produce this behaviour? Although, I didn't found a missing comma.
L.E:
I've researched more and I looked more carefully in my code and, helped by debugger, I found that my function
function (btn){}
receives as arguments on position 0: value 1, on second position receives Window (my current location) and the third argument is the one wich should've been received by my component, and it looks like ["yes", "", Object{}] etc.
And i think this is the argument I need, where 0st position is the value of my btn, but I don't know where the other arguments come from to know what I need to do to in order to make it work.
As I'm still a little confused, I'll update this with a general explanation about how I've implemented this handler.
So, at Ext.onReady I load a function init()
Then, in this function i made a var deleteButton = new Ext.Button
This button has a handler which is my initial function from question
The deleteButton is added to a new Ext.Panel with buttons:[deleteButton, etc]
This panel is added as item to a Ext.TabPanel
And, finally, TabPanel is added to a ViewPort.
The Sencha Documentation shows the implementation like:
// Prompt for user data and process the result using a callback:
Ext.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
if (btn == 'ok'){
// process text value and close...
}
});
Running the following code using ExtJs 3.4:
Ext.onReady(function(){
Ext.BLANK_IMAGE_URL = '/js/ext-3.4.0/resources/images/default/s.gif';
Ext.Msg.show({
msg: "test",
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.ERROR,
fn : function (btn, text) {
if (btn == 'yes') {
console.log(btn, text);
}
}
});
});
Output (Firebug console):
yes (an empty string)
So your code should be working. I would check to see if there are any global overrides being loaded and test it in isolation
Looking at the source it seems that the first param is the button clicked (Ext.Msg.YESNO which may give you a truthy result) but the second parameter passed is the text value you are looking for:
var handleButton = function(button){
buttons[button].blur();
if(dlg.isVisible()){
dlg.hide();
handleHide();
//here the arguments are button, activeTextEl.dom.value and opt... so look at the second argument in your callback
Ext.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value, opt], 1);
}
};
I'd try changing your code to:
function (btn, btnTxt) {
if (btnTxt == 'yes') {
document.getElementById('deleteForm:deleteCatalogPreEnreg').onclick();
}
}
First of all, thank you very much for replies.
It seemed that the problem was from a script that I was included it in my jsf page.
And that messed up parts of my code and that's why my component had a strange bahviour.
I solved it by removing that script and let the function as I posted it initially.

Meteor helper has run

How can I check all Meteor helpers have run?
When I use this code, I get a new, empty div. When I remove the code from the rendered function and run it from my console, everything works fine.
Template.CasesShow.helpers({
value: function (n) {
if (this.data) {
var result = this.data.filter(function (obj) {
return obj.name == n;
});
if (result && result[0])
return result[0].value;
}
}
});
Template.CasesShow.rendered = function () {
$(document).ready(function () {
$textarea = $('[name=1]');
var content = $textarea.val().replace(/\n/g, '<br />');
$textarea.replaceWith($('<div class="box">' + content + '</div>'));
});
};
<template name="CasesShow">
<textarea class="w-input box" placeholder="{{_ 'laborauftrag.praxis'}}" name="1" data-name="1">{{value 1}}</textarea>
</template>
So I think, Meteor hasn't inserted the value yet, which is strange because it shouldn't run the rendered function then, right?
How can I make sure Meteor has run the helpers?
Template.rendered = func will run once before your template's helper (and long before your route provides you data). Your template isn't working when you have Template.rendered function because in your rendered function, you replace your textarea with div, and in helper you're returning value which is being set on the textarea which no longer exist (because Template.CaseShow.rendered has replaced it with <div>.
If you can provide more details about what you're actually trying to achieve here, we can solve that. What you have right now is intended behaviour of meteor.
If what you want to achieve is show your content in a div but after replacing /n with <br>, I believe you can do that by performing that regexp on your data in the template helper.
Put a console.log("FIRED VALUE HELPER"); and do the same for your .rendered console.log("TEMPLATE RENDERED"); The code will log in your client browser console. For chrome I right click on the browser and choose inspect element. Then choose console from the array of logs. Your client js code would look like this:
Template.CasesShow.helpers({
value: function (n) {
console.log("FIRED VALUE HELPER");
Template.CaseShow.rendered = function () {
console.log("FIRED RENDERED");
If you don't see the log in the client browser console, the helper/rendered function did not get called.

Remove part of a table with .detach

I need a function that adds and removes a column in a table if a checkbox is checked or not. The code I got at the moment works fine to an extend. The console messages come up at the right time and the table column is correctly added to the HTML.
The problem lies in the else{} part: The columns are not removed when checkbox is unchecked. In firebug I get a message that my selector is wrong but I am not sure how to fix it. And assuming the selector was correct, is my application of .detach(this) correct?
function makevisible(idsandclasses,object,folder){
$('#checkbox'+idsandclasses).change(function() {
console.log(idsandclasses, "before if checked")
if($('#checkbox'+idsandclasses).is(':checked')){
console.log(idsandclasses, "if checked")
$('tr:contains("Details")').append('<td id="rowdetails'+folder+'">'+object.name+'</td>')
}else{
console.log("unchecked")
$('#rowdetails'+folder).detach(this)
}
})
};
Here I use the function:
$(document).ready(function() {
$("#dot0001").hover(makevisible("info0001", object0001,"object0001"))
})
This is the firebug message:
TypeError: expr.replace is not a function
expr = expr.replace( rattributeQuotes, "='$1']" )
And this is the part in my jquery-1.9.0.js file my code has problems with:
expr = expr.replace( rattributeQuotes, "='$1']" );
I assumed there is no need for the HTML. If that should be the case though let me know.
Remove this from detach. Just .detach() is sufficient.
You need to pass a selector to detach (or nothing at all its optional). You are passing this which is a DOM element. Ideally, $('#rowdetails'+folder) will match the element you are trying to detach.
Source:
http://api.jquery.com/detach/
i suppose the problem is
$(document).ready(function() {
$("#dot0001").hover(function(){
makevisible("info0001", object0001,"object0001")
})
})

How do you debug Timing Issues in Javascript?

I recently ran into a familiar javascript/jQuery timing bug and spent too long debugging it. What I need is a smarter debugging path for this problem.
In specific, my issue was that user inputs were supposed to be causing a Mongo database call and the results were sent, after a little math, to displayed outputs. But the displayed outputs were crazily wrong. However, once I added a FireBug break point the problem went away. At that point I knew I had a timing issue, but not how to solve it.
Here are the relavant pieces of code before the error:
handleDataCallBack : function(transport) {
var response = $.parseJSON(transport);
if(!hasErrors) { this.updatePage(response); }
},
accessDatabase : function(){
var params = { ... };
DAL.lookupDatabaseInfo(this.handleCallBackOutputPanel, this, params);
},
calculateValues: function() {
// some numerical values were updated on the page
}
onDomReady : function() {
// ...
//bind drop-down select change events
$('#someDropDown').change(function() {
me.accessDatabase();
me.calculateValues();
});
}
To fix the problem, all I had to do was move the "calculateValues" method from the onDomReady inside the call back:
handleDataCallBack : function(transport) {
var response = $.parseJSON(transport);
this.calculateValues();
if(!hasErrors) { this.updatePage(response); }
},
The problem was that the database hadn't responded before the calculations were started. Sure, that's easy to spot in retrospect. But what methods can I use to debug asynchronous timing issues in javascript/jQuery in the future? This seems well outside the context of IDE tools. And FireBug didn't help. Are there any tools for tracking down asynchronous web development issues? Or maybe some time-tested methods?
i assume your problem is caused here:
$('#someDropDown').change(function() {
me.accessDatabase();
me.calculateValues();
});
this issue is that your calculations are done just right after the call. seeing that the DB call is async, calculate does not wait for it. however, you can do it using "callbacks". i see you do try to implement it and yes, it is correct. however, i find this more elegant:
calculateValues: function() {
// some numerical values were updated on the page
},
//since this is your general callback hander
//you hand over the return data AND the callbackAfter
handleDataCallBack: function(transport, callbackAfter) {
var response = $.parseJSON(transport);
//you may need to use apply, im lost in scoping here
callbackAfter();
//or
callbackAfter.apply(scope);
if (!hasErrors) {
this.updatePage(response);
}
},
accessDatabase: function(callbackAfter) {
var params = {};
//pass callbackAfter to the function,
//after this is done, pass it to the handler
DAL.lookupDatabaseInfo(this.handleCallBackOutputPanel, this, params, callbackAfter);
},
onDomReady: function() {
$('#someDropDown').change(function() {
me.accessDatabase(function() {
//send over what you want done after.
//we'll call it "callbackAfter" for easy tracing
me.calculateValues();
});
});
}​

Categories