Call method inside function - javascript

i have a wizard from a metronic theme where I'm trying to call a function to check if my array contains dublicates.
if I remove this part of my code it works without problems.
console.log(this.checkIfArrayIsUnique());
code
var wizard = (<any>$('#m_wizard')).mWizard();
//== Validation before going to next page
wizard.on('change', function(wizard) {
if(wizard.getStep() > 2){
console.log(this.checkIfArrayIsUnique());
}
mApp.scrollTop();
})
Right now my checkIfArrayIsUnique() is just a dummy function
checkIfArrayIsUnique()
{
return true;
}
how can i call a method outside my 'change' event ? So I'm able to run thru my array and confirm it does not have any dublicates.

the problem is the "function(wizard)" call, since it creates a new scope. But your checkIfArrayIsUnique() ist actually outside of this scope.
Try using ES6 function syntax
wizard.on('change',(wizard) => {
if(wizard.getStep() > 2){
console.log(this.checkIfArrayIsUnique());
}
mApp.scrollTop();
})
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

in your change function the variable this point to current function,to use it,you should make this point to out object,you should write like this:
var that = this;
var wizard = (<any>$('#m_wizard')).mWizard();
//== Validation before going to next page
wizard.on('change', function(wizard) {
if(wizard.getStep() > 2){
console.log(that.checkIfArrayIsUnique());
}
mApp.scrollTop();
})

Related

How to use Callback functions in Class with JavaScript/jQuery

I have a class I am using for creating CRUD Objects for my site.
It stores the form and table paths for adding, listing, editing and deleting the data, as well as reloading your view with ajax after each edit.
Here is my class definitions:
class CRUDObj{
constructor(containerSel, links) {
this.links = links;
this.containerSel = containerSel;
this.formCallBack = function(){};
}
setActive(obj_id){
$.post(this.links.editURL+'?'+obj_id, {status:"active"}, this.reload);
}
reload(returnData){
this.formCallBack(returnData);
this.formCallBack = function(){};
if($(this.containerSel).length > 0){
ajaxLoad(this.links.listURL, $(this.containerSel));
}
}
}
A basic instance of initializing it:
var contactObj = new CRUDObj('#contacts', {
editURL: '/contact.edit.php',
listURL: '/contacts.list.php',
});
contactObj.formCallBack = function(){
console.log('Custom Reload Callback');
};
The problem appeared when I tried to add the callback, so that I could run a custom function during the refresh.
Running contactObj.setActive(); works properly, and my refresh function is called after the form submits, but when it hits my callback I get:
Uncaught TypeError: this.formCallBack is not a function
Calling it manually contactObj.refresh(); works smoothly.
How can I pass this callback function through better?
The problem is that you're passing method as function, so you loose this context. this will be window object or undefined (if using strict mode):
You need this:
var self = this;
lightboxForm(this.links.editURL+'?'+obj_id, function(x) { self.reload(x) });
or using ES6
lightboxForm(this.links.editURL+'?'+obj_id, x => this.reload(x));
or using bind to return function with given context:
lightboxForm(this.links.editURL+'?'+obj_id, this.reload.bind(this));

Can I add a variable or a function in a mdDialog?

I want to add a variable or a function to my mdDialog. Im not to sure on how to create a custom mdDialog, Im new to angularjs.
This is my mdDialog:
vm.dialog_up = function() {
vm.dis = true;
alert = $mdDialog.alert()
.title('Attention, ')
.content('Do you want to edit your Information?')
.ok('Close');
$mdDialog
.show( alert )
.finally(function() {
alert = undefined;
});
}
I want to maybe add a function to the .ok button.
JavaScript is a very liberal language and it allows you to add properties and methods to objects. For example:
var modal = {};
modal.x = 5;//this assigns the value of `5` to the newly attached property `x`
modal.testMethod = function() {
//Do something here
}
PS:
Though personally, I think that modifying framework objects can cause side effects.

Changing the state of a toggle in JavaScript/jQuery

Is it possible to change the state of a toggle function? Like:
myDiv.toggle ... function 1 , function 2
I click on the myDiv element, the function 1 executes
I click again, function 2
I click again, function 1
BUT
Change the state
function 1 again
etc.
But I need to be able to change the state from outside the toggle function.
Here is a javascript object that uses closure to track it's state and toggle:
var TOGGLER = function() {
var _state = true;
var _msg = "function1";
var function1 = function() {
_msg = "function1";
}
var function2 = function() {
_msg = "function2";
}
return {
toggle: (function () {
_state = !_state;
if (_state) {
function1();
} else {
function2();
}
return _msg;
})
}
}();
Here is a jsfiddle that shows how to use it to toggle based with the following jquery: http://jsfiddle.net/yjPKH/5/
$(document).ready(function() {
$("#search").click(function() {
var message = TOGGLER.toggle();
$("#state").text(message);
});
});
The toggle function is meant for simple use cases. Changing the state externally is not "simple" anymore.
You cannot easily/safely (it's internal so it may change during minor versions) access the state variable of the toggle function easily as it's stored in the internal dataset of the element.
If you really want to do it, you can try this code though:
$._data(ELEMENT, "lastToggle" + func.guid, 0);
func is the function you passed to .toggle(), so you need to save this function in a variable. Here's a minimal example: http://jsfiddle.net/xqgrP/
However, since inside the function there's a var guid = fn.guid || jQuery.guid++ statement, I somehow think that the devs actually meant to use guid instead of func.guid for the _data key - in that case a minor update is very likely to break things. And after the fix you'd have to iterate over the data set to retrieve the correct key as there is no way to access the guid from outside.

How to change the order of which they are called?

I have a quite inconvenient problem.
Say that I have the following functions
function name(namearg){
...
..
}
function handlefailed(){
..
..
}
function handlecover(){
..
..
}
Now to my problem, I have alot of hard coded html that can't be changed that is calling both functions like this
Link
Link
Link
The problem is the order of which I'm calling the functions, I first want to see which function that is called, either handlefailed() or handlecover(), and then want to know what name that is sent to the name function.
If I would have called the functions in the other way around I would just have done
var theName;
function name(namearg){
theName = namearg
}
function handlefailed(){
callOtherfunctionInAnotherJavascript(getElements(theName + ".failed"));
}
function handlecover(){
callOtherfunctionInAnotherJavascript(getElements(theName + ".cover"));
}
But now this is not possible since I'm calling the name function after the first function.
Is there a way in javascript that "changes" the order of how the functions are evaluated, or do you guys have a clever sollution to my problem, I.E getting the value of the namearg variable and use it in the handlefailed() & handlecover() functions?
var postFix;
function name(namearg){
callOtherfunctionInAnotherJavascript(getElements(namearg + postFix));
}
function handlefailed(){ postFix = '.failed'; }
function handlecover(){ postFix = '.cover'; }
you can empty both functions:
function handlefailed(){
..
..
}
function handlecover(){
..
..
}
and create two new functions that doing what you need
function handlefailed2(){
..
..
}
function handlecover2(){
..
..
}
then call the new functions from inside function name(namearg) according namearg deside to which function you want to call
You can declare another global, handleFunc, and have handlefailed/handlecover assign which one to call in name.
var theName;
var handleFunc = null;
function name(namearg)
{
if(handleFunc instanceof Function)
{
handleFunc(namearg);
handleFunc = null;
}
theName = namearg
}
function handlefailedCallback(namearg){ /* some code */}
function handlefailed()
{
handleFunc = handlefailedCallback;
}
function handlecoverCallback(namearg){ /* some code */}
function handlecover()
{
handleFunc = handlecoverCallback;
}
This gives you the flexibility to continue using name without breaking other areas of the code.

Jquery click bindings are not working correctly when binding multiple copies

I seem to have an issue when creating copies of a template and tying the .click() method to them properly. Take the following javascript for example:
function TestMethod() {
var test = Array();
test[0] = 0;
test[1] = 1;
test[2] = 2;
// Insert link into the page
$("#test_div").html("<br>");
var list;
for (x = 0; x < test.length; x++) {
var temp = $("#test_div").clone();
temp.find('a').html("Item #" + test[x]);
temp.click(function () { alert(x); });
if (list == undefined)
list = temp;
else
list = list.append(temp.contents());
}
$("#test_div2").append(list);
}
The problem I am seeing with this is that no matter which item the user clicks on, it always runs alert(2), even when you click on the first few items.
How can I get this to work?
Edit: I have made a very simple example that should show the problem much clearer. No matter what item you click on, it always shows an alert box with the number 2 on it.
Correct me if I'm wrong, .valueOf() in JS returns the primitive value of a Boolean object.....
this would not happen ShowObject(5,'T');... ShowObject(objectVal.valueOf(), 'T');
why not use objects[x].Value directly? ShowObject(objects[x].Value, 'T');
WOOOOOSSSHHHH!
after searching deeply... I found a solution...
because it's a closure, it won't really work that way...
here's a solution,
temp.find('a').bind('click', {testVal: x},function (e) {
alert(e.data.testVal);
return false;
});
for best explanation, please read this... in the middle part of the page where it says Passing Event Data a quick demo of above code
I think your issue arises from a misunderstanding of scopes in JavaScript. (My apologies if I'm wrong.)
function () {
for (...) {
var foo = ...;
$('<div>').click(function () { alert(foo); }).appendTo(...);
}
}
In JavaScript, only functions create a new scope (commonly referred to as a closure).
So, every round of the for loop will know the same foo, since its scope is the function, not the for. This also applies to the events being defined. By the end of looping, every click will know the same foo and know it to be the last value it was assigned.
To get around this, either create an inner closure with an immediately-executing, anonymous function:
function () {
for (...) {
(function (foo) {
$('<div>').click(function () { alert(foo); }).appendTo(...);
})(...);
}
}
Or, using a callback-based function, such as jQuery.each:
function () {
$.each(..., function (i, foo) {
$('<div>').click(function () { alert(foo); }).appendTo(...);
});
}
For your issue, I'd go with the latter (note the changes of objects[x] to just object):
var list;
jQuery.each(data.objects, function (x, object) {
// Clone the object list item template
var item = $("#object_item_list_template").clone();
// Setup the click action and inner text for the link tag in the template
var objectVal = object.Value;
item.find('a').click(function () { ShowObject(objectVal.valueOf(), 'T'); }).html(object.Text);
// add the html to the list
if (list == undefined)
list = item;
else
list.append(item.contents());
});

Categories