1

I'm trying my hand at using Addy Osmani's prototype pattern.

I have an object "app" and, upon a submission of a form, I'm trying to call a function inside of my init function. But it isn't console.logging...

$(document).ready(function() {
 var app = {
 logHello: function() {
 console.log('hello');
 },
 initialize: function() { 
 $('#userlogin').on('submit', function(){
 this.logHello;
 return false;
 });
 }
 }
 app.initialize();
});

Where am I going wrong?

asked Sep 12, 2013 at 17:41
2
  • Inside a jQuery event handler, this refers to the element (explicitly set by jQuery). So this.logHello, which would do nothing anyways because you aren't calling anything, refers to something that doesn't exist Commented Sep 12, 2013 at 17:43
  • So how would I remedy the 'this' error then? Commented Sep 12, 2013 at 17:44

3 Answers 3

3

this is now referring to your jQuery on submit function, try using a context variable of this (also, you need () after you call your function):

var self = this;
$('#userlogin').on('submit', function(){
 self.logHello();
 return false;
});

Demo: http://jsfiddle.net/59Y9z/

answered Sep 12, 2013 at 17:44
Sign up to request clarification or add additional context in comments.

Comments

3
 initialize: function() { 
 var self=this;
 $('#userlogin').on('submit', function(){
 self.logHello();
 return false;
 });
 }

this keyword changes according to the function scope, a function in another function creates a new scope ,unless it is bound to a scope somehow.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

answered Sep 12, 2013 at 17:44

Comments

2

It's an issue of scope. Within the submit event handler, the this variable refers to the function's scope and not the scope of app where your logHello function resides.

Try something like this :

...
initialize: function() {
 var old_scope = this; // save the scope into a local variable
 $( '#userlogin' ).on( 'submit' , function() {
 old_scope.logHello;
 return false;
 });
},
...

The variable old_scope will now contain the scope of app, so you'll be able to access all of the variable and functions that app holds.

answered Sep 12, 2013 at 17:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.