brandonhowlett brandonhowlett - 1 year ago 101
Javascript Question

Calling a method inside another method of same class

I admittedly know little javascript, jquery, or oop, but I know enough to piece things together and sometimes get them to work. This however is over my head, and despite what I google I can't make heads or tails of what's going on. This is the gist of my code:

jQuery(document).ready(function($) {

var methods = {
init : function( options ) {
if (somthing) {
this.latlng(input);// <--- ERROR: Object has no method
auto : function( ) {
if (something) {
} else {
location : function ( input ) {
// draw map
latlng : function ( input, l ) {
// draw map

$.fn.codeAddress = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.tooltip' );

var geo = new $(document).codeAddress(); // Initialize the object

I relied on jQuery Docs Plugin/Authoring as my template and began piecemealing from there. Ideally it loads init() on it's own when the document is ready, but it wouldn't so I added the second to last line to initialize the object.

A map is initially created in init() using method latlng() to draw it. That's where I get the error on line 6, this.latlng(input) Uncaught TypeError: Object [object Object] has no method 'latlng'. Thereafter an onclick eventhandler calls auto() to redraw the map depending on the input it receives.

I apologize if my explanation and/or code is a junkshow. I'm trying to learn as I go.

Answer Source

In the code of jQuery plugins, this is a reference to the jQuery object wrapping the DOM element being iterated over at the time.

In your case, you've manually attached your plugin to document.
(You should do this in your site's code, not inside the plugin file)

In any case, instead of calling this.latlng() you can reference your plugin with this.codeAddress( 'latlng' );.

This is the intended functionality of jQuery plugins, and it keeps things clean if you access them this way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download