JS Jquery Namespace Calling Functions - javascript

Ok terrible title but I couldn't think of another description.
I have the following code:
jQuery( document ).ready( function( $ )
{
$.myNamespace = {
init: function()
{
$('.button').click(function() {
this.anotherFunction();
});
},
anotherFunction: function()
{
alert('insidefunction');
}
}
$.myNamespace.init();
});
As you can see I am trying to call anotherFunction from inside init and have there the two ways I tried but didn't work. So how am I able to call that function or is my concept wrong?

jQuery( document ).ready( function( $ )
{
$.myNamespace = {
init: function()
{
var a=this;
$('.button').click(function() {
a.anotherFunction();
});
},
anotherFunction: function()
{
alert('insidefunction');
}
}
$.myNamespace.init();
});
http://jsfiddle.net/ZpAtm/2/

Absolutely calling it within the click handler changes things, as this inside any jQuery event handler is set to the element that caused the event.
Instead, try using the following pattern:
jQuery(document).ready(function($) {
$.myNamespace = (function() {
function init() {
$('.button').click(function() {
anotherFunction();
});
}
function anotherFunction() {
alert('insidefunction');
}
// return an object with all the functions you want
// available publically as properties. Don't include
// any "private" functions.
return {
init: init,
anotherFunction: anotherFunction
};
})();
$.myNamespace.init();
});​

Related

Reading a function from another function

The problem that when I click on .test it does not execute the do_alert(); function and gives me a error:
do_alert(); is not defined.
What's the problem? the main function helpers is already read when the page is loaded why can' get this function from logout_users function?
var setup_system = (function($) {
"use strict";
return {
init: function() {
this.logout_users();
this.helpers();
},
logout_users: function() {
$(document).on('click', '.test', function(e) {
e.preventDefault();
do_alert();
});
},
helpers: function() {
function do_alert() {
alert();
}
}
};
})(jQuery);
jQuery(document).ready(function() {
setup_system.init();
});
NOTE: I try to re-read the helpers function by adding this.helpers() inside logout_users function but nothing change.
It's because you've defined do_alert() within the scope of the helpers function.
To fix this you will need to move that function to within scope of the object you return. You could either put it at root level of the object (which would work fine, but could get messy if you have a lot of 'helper' functions) or you could nest it within your helpers property if you define that as another object. Personally, I'd use the latter to have some semblance of organisation. Try this:
var setup_system = (function($) {
"use strict";
return {
init: function() {
this.logout_users();
},
logout_users: function() {
var _obj = this;
$(document).on('click', '.test', function(e) {
e.preventDefault();
_obj.helpers.do_alert();
});
},
helpers: {
do_alert: function() {
alert('foo');
}
}
};
})(jQuery);
jQuery(function() {
setup_system.init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Click me</div>
Note that I cached the reference to the object as _obj outside of the click handler, as within that block this will refer to the clicked .test element.
Do_alert function exist only in helpers method, so you can't access to it.
You need to declare your function directly in the logout_user method or outside, try this :
var setup_system = (function ($) {
"use strict";
return {
init: function () {
this.logout_users();
this.helpers();
},
logout_users: function() {
function do_alert(){
alert();
}
$(document).on('click', '.test', function(e){
e.preventDefault();
do_alert();
});
},
helpers: function () {
function do_alert(){
alert();
}
}
};
})(jQuery);
jQuery(document).ready(function () {
setup_system.init();
});
When helpers is invoked by the initfunction, all that is happening is that do_alert is being declared. But function declarations are hoisted to the top of their lexical scope. The lexical scope of do_alert is the scope defined by the helpers function. Therefore, do_alert is not accessible outside of helpers function.
A couple things you could do. The first one that comes to mind is: you could have the helpers method define a method called do_alert on the object being returned rather than merely declaring a function, like so:
helpers: function() {
this.doAlert = function() {
alert();
}
}
When your doAlert() is invoked by the event handler passed to jQuery, it will not work with the above solution. Instead you will need to make sure you call that doAlert on the returned object in that event handler. This is how you can do that:
logout_users: function() {
var self = this;
$(document).on('click', '.test', function(e) {
e.preventDefault();
self.doAlert();
});

How to call function inside jquery plugin after plugin is initialised

I', creating my own jQuery plugin which can be assigned to more than one element in document. I want, on some events, to call a function inside plugin for that particular element, but everything is driving me crazy. Plugin, itself, works, but problem with external calling exists.
simple plugin:
(function ( $ ) {
$.fn.myPlugin = function (options) {
var settings = $.extend({
someOption: ""
}, options);
return this.each(function () {
_init();
_load();
});
function _init() {
//some action..
}
function _load() {
//some action..
}
};
$.fn.myPlugin.reload = function () {
_load(); //or this._load();
}
}( jQuery ));
and in html:
<div id="div1"></div>
<button id="button1">Click to reload</div>
<script>
$(document).ready(function() {
var A=$("div1").myPlugin({
someOption:"someValue"
});
$("#button1").click(function(){
A.reload();
});
});
</script>
return is always that _load() is undefined... Any idea will be really appreciated.
Youre returning before you define the functions, also _load cannot be accessed from the reload function if its not in a higher scope:
(function ( $ ) {
//function definitions:
function _init() {
//some action..
}
function _load() {
//some action..
}
$.fn.myPlugin = function (options) {
var settings = $.extend({
someOption: ""
}, options);
return this.each(function () {
_init();
_load();
});
};
$.fn.myPlugin.reload = function () {
_load(); //
}
}( jQuery ));
Note that it can be accessed like this:
$.myPlugin.reload();
Reload is not part of an myPlugin instance.
If you want to return a custom object for each instance do this:
(function ( $ ) {
$.fn.myPlugin = function (options) {
var settings = $.extend({
someOption: ""
}, options);
//function definitions:
function _init() {
//some action..
}
function _load() {
//some action..
}
//iterate
this.each(function () {
_init();
_load();
});
return {
reload:_load,
};
};
}( jQuery ));
Now you can do
$("test").myPlugin().reload();
A is holding a reference to a jQuery object and as such has all the methods of $.fn.
But your reload is not a method of $.fn but of $.fn.myPlugin.
If you fix this and take Jonas` answer into account then it should work;)

How bind a event and use apply/call to change the scope

+function ($) {
'use strict';
var popup = {
init: function(element) {
this._active = 'products__popup--active';
this._product = $('.products__popup');
this._element = $('[data-popup-to]');
this._TIME = 500;
popup.attachEvt();
},
attachEvt: function() {
var that = this;
that._element.bind('click', popup.handlerEvt.call(that));
},
handlerEvt: function() {
console.log(this);
console.log('test');
}
};
$(window).on('load', function() {
popup.init();
});
}(jQuery);
I have this script, and is not working yet, I cant show you a working example because it is not ready, I'm organizing the code first.
And there is a problem with the attachEvt function, inside it I want to call another function of my object, this function will bind a click in the that._element, but I want pass to the handlerEvt the scope of this (the clicked element) and the that (the object), but this is not working:
that._element.bind('click', popup.handlerEvt.call(that));
I'm just passing the that scope and when the script loads, the element will be clicked without click, I want avoid this.. this is possible?
UPDATE:
Resuming:
I want be able to use the scope of the object (that) and the scope of the clicked element (this) inside the handlerEvt function, but without make the event click when the script loads.. :B
Try utilizing .bind() , with this set to that._element , that passed as parameter to handlerEvent . Note order of parameters at handlerEvent: obj: that first , evt event object second
+function ($) {
'use strict';
var popup = {
init: function(element) {
this._active = 'products__popup--active';
this._product = $('.products__popup');
this._element = $('[data-popup-to]');
this._TIME = 500;
popup.attachEvt();
},
attachEvt: function() {
var that = this;
that._element.bind('click', popup.handlerEvt.bind(that._element, that));
},
handlerEvt: function(obj, evt) {
console.log(evt, obj, this);
console.log('test');
}
};
$(window).on('load', function() {
popup.init();
});
}(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div data-popup-to="true">click</div>

Function being run when bind in jquery document ready

I'm trying to bind a click event to the function below, however the entire function is currently being run when being binded in the document ready.
Is it possible to run it solely on the click event? Possibly it has something to do with the way my method is composed?
Thanks in advance
$(function() {
$("#expand-search").on("click", search.resize());
});
var search = {
element: $('#search_advanced'),
resize: function() {
search.element.slideToggle(400, 'swing', search.buttonState());
},
buttonState: function() {
if(search.element.is(':hidden')) {
console.log('hidden');
} else {
console.log('visible');
}
}
};
You are calling the function (handler) instead of passing the reference (name) of function (handler) to on().
Change
$("#expand-search").on("click", search.resize());
To
$("#expand-search").on("click", search.resize);
No parenthesis to event handlers! You want to pass the function-to-be-executed, not the result from executing it. Also, you will need to move your search object inside the ready handler since you use selectors for its initialisation.
$(function() {
var search = {
element: $('#search_advanced'),
resize: function() {
search.element.slideToggle(400, 'swing', search.buttonState);
},
buttonState: function() {
if(search.element.is(':hidden')) {
console.log('hidden');
} else {
console.log('visible');
}
}
};
$("#expand-search").on("click", search.resize);
});

Is there a way to pass context to bind in jQuery?

I'm inside a javascript object (vr roxx :) ), but every time I do an event bind with jQuery I have to include the main object instance's context through the data parameter in order to work with it. Isn't there an easy/neat way to do this in jQuery?
var oink =
{
pig: null,
options:
{
showPigMom: 0
},
init: function(pigObj)
{
//Show the pigmom
$(this.doc).bind('keyup click', {o: this}, function(e)
{
var o = e.data.o;
if (o.options.showpath)
o.doWhatever();
});
...
I use the $.proxy() function
init: function(pigObj)
{
//Show the pigmom
$(this.doc).bind('keyup click', $.proxy(function(e) {
if (this.options.showpath)
this.doWhatever();
$(e.currentTarget).text(); // use this to access the clicked element
}, this));
}
init: function() {
var self = this;
$(this.doc).bind('keyup click', function() {
if (self.options.showpath) self.doWhatever();
});
}
init: function() {
$(this.doc).bind('keyup click', function() {
if (this.options.showpath) this.doWhatever();
$(e.currentTarget).text(); // use this to access the clicked element
}.bind(this))
}

Categories