Lash Doni Lash Doni - 3 months ago 7
Javascript Question

Needs to understand Backbone main function

I'm trying to learn advance JavaScript and some people suggested to learn from Backbone.js source code

(function(factory) {

//There are some lines of code here...

})(function(root, Backbone, _, $) {

//Many lines of code here

});



  • Is the
    factory
    in
    (function(factory)
    , the root that is in
    (function(root, Backbone, _, $)
    ?

  • What is factory?

  • What is Backbone?

  • What is _?

  • What is $?


Answer

You are looking at the AMD module pattern, which I wouldn't spend too much time focusing on. factory is the function with "Many lines of code". The first function you encounter calls factory after it loads Backbone's dependencies - underscore.js (_) and jquery.js ($). Think of it as a dependency-injection version of:

<script src="jquery.js"></script>
<script src="underscore.js"></script>
<script>
function Backbone() {
  // do stuff that depends on underscore and jquery
}
</script>

Is the factory in (function(factory), the root that is in (function(root, Backbone, _, $)?

No, answered above

What is factory?

The guts of the Backbone library which is initialized once its dependencies are loaded

What is Backbone?

An empty object to start out with root.Backbone = factory(root, exports, _, $); where exports is initialized to {} for a given module

What is _?

The underscore.js library

What is $?

The jquery library