0

I am trying to figure out JavaScript namespaces... I would like to write couple of functions and secure them in namespaces like below.. but I think I don't get it very well..This is too simple question but it will be clear for me I guess If I see why that doesn't work..

Here an exp that I am trying:

var myApp = { 
    getTxt: function(x){
        x.click(function(){
        var txt = $(this).html();
        alert(txt);
        });
    };    
};

call myApp:

var box = $('.js-box');
alert(myApp.getTxt(box));

I think MyApp is created rightly but I am not sure about calling and firing the getTxt function..

Calling that:

  myApp.getTxt(box)

doesn't mean to fire x.click function..? Why does it turn an object?

What am I doing wrong here? Thanx!

http://jsfiddle.net/67b02cht/1/

Mar
  • 1,526
  • 6
  • 21
  • 46

2 Answers2

0

You are defining myApp as an object, So here is a problem, You are giving ; after defining the field, which you can't. It'll cause a syntax error.

var myApp = { 
    getTxt: function(x){
        x.click(function(){
        var txt = $(this).html();
        alert(txt);
        });
    }                //<<<<-------------here was a semicolon,
};

And you are calling the function like bellow in alert it will cause an undefined alert because you are not returning anything from the function. Just call

myApp.getTxt(box)

And it will show the content on click.

DEMO

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
0

How about a modular approach.

var MyApp = MyApp || {};
MyApp.Module = (function () {
  function App() {
  }
  App.prototype.getTxt = function(x){
    //your code here
  }
  return App;
})();

Use it this way:

var box = $('.js-box');    
alert(new MyApp.Module.getTxt(box));
bring2dip
  • 886
  • 2
  • 11
  • 22