method with parameter in unknown js function issues - javascript

I'm trying to protect a part of my js code wrapping my code with an Unknown function.
I have edit my function to change
function banana(url) {}
to method
banana: function(url){ },
when I try to call my function banana in another function i try to use
this.banana(url);
but i have this error:
TypeError: this.banana is not a function
Full code:
(function (){
var url_test = "./add_user.php?opt=get_user&token=<?php echo $token; ?>";
if (typeof $.customfnc == 'undefined')
$.customfnc = {}
$.customfnc.get = {
setup: function (){
var url = "google.ca";
this.banana(url);
},
banana: function (url){
console.log("my url: " + url);
};
};
};
// on ready render data
$(document).ready(function() {
$.customfnc.get.setup();
});
})(jQuery);
thanks for your help!

The issue here is that the scope of 'this' is not exactly what you might think it is.
The way I have handled this particular issue in the past is to add
var self = this;
Outside of the object that is attempting to self reference. This may impact how you have set up youre .get() object though.
$.customfnc.get = function(){
var self = this;
self.setup = function (){
//....
self.banana(URL)
}
self.banana = function(url){
//...
}
}

Related

How can I pass variables to external javascript file that can be accessed by all the functions

I have a Kendo grid whose Events property is hooked to a function(Grid_OnRowSelect) in external javascript file. There are other functions in the external javascript file ( like on button click * $("#btnS").on('click', function () {....* ) and few others. The Grid_OnRowSelect function and the other functions use common set of variables. How can I pass variables to an external javascript file from a view (cshtml) that can be accessed by all the functions.
#(Html.Kendo().Grid<MyModel>()
.Name("rGrid")
.Events(events => events.Change("Grid_OnRowSelect"))
.Columns(columns =>
{
columns.Command(command =>
.......
.......
.......
The external js file is
var MYFunc = MYFunc || (function () {
var _args = {}; // private
return {
init: function (Args) {
_args = Args;
// some other initialising
},
helloWorld: function () {
alert('Hello World! -' + _args[0]);
},
Grid_OnRowSelect: function (e) {
var data = this.dataItem(this.select());
detailRequestID = data.ID;
var url = _args[1] + "/" + detailRequestID;
window.location.href = url;
},
onError: function (e, status) {
//alert("A server error has occurred!");
var url = _args[2];
window.location.href = url;
}
};
}());
How I'm trying to pass arguments
<script>
window.onload = function(){
var searchUrl = #Url.Action("Search");
var updateUrl = #Url.Action("Update");
var errorUrl = #Url.Action("ServerError", "Error");
};
MYFunc.init([searchUrl, updateUrl, errorUrl]);</script><script src="~/Scripts/Index.js"></script>
But when Grid_OnRowSelect or any of the functions gets executed _args is undefined. What is not correct?
Thanks.
If you just declare a variable outside of a function in javascript it will be available to all code JS code that is loaded AFTER it. The fact that the file is external does not matter, just that it loads into the DOM after the place where you set your global variables.
Example
var globalVar = "I am global";
function test(){
var copy = globalVar;//copy now == "I am global"
var nonglobalVar = "I am not";//this is local to the function
}
var global2 = globalVar;//global2 now == "I am global"
var anotherVar = nonglobalVar;//this line will throw an error because variable is out of scope.
Another common tactic is to write your values to a hidden field in the html and then access that from your external functions.

Passing variable into object method javascript

trying to get my head around objects, methods, closures, etc... in Javascript.
Can't see why this isn't working, some fundamental flaw in my thinking I guess. I'm expecting the val variable to be passed through to the addNote() function but it isn't. I thought that any variables declared outside of a function are available to that function, as long as they're not within another function. Is that not correct?
if(typeof(Storage) !== "undefined") {
console.log(localStorage);
var $input = $('#input'),
$submit = $('#submit'),
$list = $('#list'),
val = $input.val();
var noteApp = {
addNote : function(val) {
var item = val.wrap('<li />');
item.appendTo($list);
clearField();
},
clearField : function() {
$input.val = '';
},
delNote : function(note) {
}
};
$submit.on('click', function(){
noteApp.addNote();
});
} else {
}
I'm trying to learn how the pros manage to get their code so clean, concise and modular. I figured a note app would be a perfect start, shame I got stuck at the first hurdle...
Cheers.
There are several issues with the code in the question
defining an argument named val and not passing an argument to the function
when calling clearField() inside the object literal it's this.clearField()
You're only getting the value once, not on every click
val is a string, it has no wrap method
$input.val = ''; is not valid jQuery
I would clean it up like this
var noteApp = {
init: function() {
if (this.hasStorage) {
this.elements().events();
}
},
elements: function() {
this.input = $('#input');
this.submit = $('#submit');
this.list = $('#list');
return this;
},
events: function() {
var self = this;
this.submit.on('click', function(){
self.addNote();
});
},
hasStorage: (function() {
return typeof(Storage) !== "undefined";
})(),
addNote: function() {
this.list.append('<li>' + this.input.val() + '</li>');
this.clearField();
return this;
},
clearField: function() {
this.input.val('');
},
delNote : function(note) {
}
}
FIDDLE
Remember to call the init method
$(function() { noteApp.init(); });
In your call to addNote(), you don't pass any argument for the val, so it will be undefined:
noteApp.addNote();
// ^^ nothing
Pass the input (seems you want the jQuery object not the string value because of your val.wrap call):
noteApp.addNote($input);
When you declare the val in the function, it is scoped to that function and will only be populated if the function call passes a value for that argument. Even if you have another variable in an upper scope with the same name val, they are still differentiated. Any reference to val in the function will refer to the local val not the upper scope.

JS object method call not working from callback

I have a small problem with prototyped JS coding, and with callbacks. It looks like not working properly.
Here is my sample:
var hl = new HeaderLogin;
hl.drawPanel();
var HeaderLogin = function(elem) {
this.init = true;
this.jsvh = JSViewHandler.getInstance();
};
HeaderLogin.prototype.drawPanel = function() {
var self = this;
...
this.jsvh.get({
...
'callback': function(rsp, templates) {
...
$('#jsview_user_login_form').ajaxForm({success: asd});
}
});
function asd(rspJSON, statusText, xhr, $form) {
self.showResponse(rspJSON, statusText, xhr, $form);
}
};
HeaderLogin.prototype.showResponse = function(rspJSON, statusText, xhr, $form) {
if (typeof this.init === 'undefined') {
alert('not an object');
}
...
}
I have to call the showResponse function after the form has been sent, but if I use the {success: self.showResponse} the init will not exists. It looks like a static call and I can't access any variable from the constructor. If I create a local asd function and I use it as the success callback the showRespons will know about the constructor variables.
I don't want to use this extra function, if you have any solution about this problem, please let me know!
Thanks a lot guys! :)
SOLUTION:
success: self.showResponse.bind(self)
I have not done this in a long time, but can you try with
'callback': function(rsp, templates) {
...
var s = self;
$('#jsview_user_login_form').ajaxForm({success: s.showResponse});
}

Issue while defining jQuery functions

Trying to define a couple of functions like so:
user = (function() {
var friends_list = (function() {
$.get('/ajax/user/friends_list', function(data) {
......
So I can later on call them when need it like so user.friends_list() but for now, the only thing I get is this following error:
TypeError: Object function () {
var friends_list = (function() {
$.get(....
I just don't know where else to look, any suggestions?
You need to create user as an object, in your case the friends_list is a closure method, it will be availble outside the function
user = {
friends_list : function(){
....
}
}
make a user object and not function
var user = {
friends_list : function(){
$.get('/ajax/user/friends_list', function(data) {
......
}
}
and call it like.. user.friends_list()
fiddle here
You're using a closure here, so friend_list is invisible on the outside of user.
If you want to use closures, to hide some variables, to best way to export friend_list would be:
(function(){
var somePrivateVariable;
window.user = {};
window.user.friend_list = function() {
// make use of somePrivateVariable...
};
})();
user = function() {
this.friends_list = function() {
$.get('/ajax/user/friends_list', function(data) {
......
});
};
return this;
};
Above should also work.
reference http://www.w3schools.com/js/js_objects.asp
You can check out this link
Here is the code:
var global = {};
global.sayHello = function (x){
//do your code here
console.log('Hello ' + x );
};
global.sayHello('Kevin');
user = new function(){
var private_variable;
function private_method(){}
this.global_variable = '';
this.global_method = function(){};
}

Invoke public function from internal/private function?

Just wondering if I'm missing something or not but I attempted to do the following:
(function() {
var thing = function() {
var doIt = function() {
console.log("just do it");
this.updateValue(5);
};
return {
updateValue: function(val) {
console.log('updating value: ' + val);
},
go: function() {
doIt();
}
}
};
var t = thing();
t.go();
}())
This results in "just do it" showing up in the console followed by an error b/c it says "updateValue" is not a function.
I was wondering, can an internal/private function (e.g. "doIt") invoke a public function (e.g. "updateValue")? Perhaps this is just bad design and you should never really want to do this and I've actually refactored my code to avoid/not do this but I was curious if it was possible.
Thanks in advance.
Either use call/apply to explicitly specify the context for this (like #SLaks and #Alnitak) mentioned or else define the function at the beginning and then add it as a property to the returned object:
var thing = function() {
var updateValue = function () { /* */ },
doIt = function() {
console.log("just do it");
updateValue(5);
};
return {
updateValue: updateValue, // minor duplication here
go: function() {
doIt();
}
};
};
If the minor duplication annoys you, you can also do this:
var thing = function() {
var exposed = {
updateValue: function(val) {
console.log('updating value: ' + val);
},
go: function() {
doIt();
}
}, doIt = function() {
console.log("just do it");
exposed.updateValue(5);
};
return exposed;
};
Writing doIt(), calls the function in the global context, so this is the window object.
You need to write doIt.call(this) to pass your this as the context for doIt.
Per #SLaks answer, this is incorrect when invoked by doIt().
Instead, try:
doIt.call(this);

Categories