Alex
Alex

Reputation: 7688

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?

Upvotes: 0

Views: 64

Answers (6)

3y3
3y3

Reputation: 802

user = new function(){
   var private_variable;
   function private_method(){}

   this.global_variable = '';
   this.global_method = function(){};
}

Upvotes: 0

rahul maindargi
rahul maindargi

Reputation: 5655

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

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388406

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(){
        ....
    }
}

Upvotes: 2

KevinIsNowOnline
KevinIsNowOnline

Reputation: 773

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');

Upvotes: 0

Michal Rus
Michal Rus

Reputation: 1848

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...
    };
})();

Upvotes: 1

bipen
bipen

Reputation: 36541

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

Upvotes: 1

Related Questions