Click here to Skip to main content
15,895,656 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

Following is my code:

HTML:

HTML
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Using Require js for modular loading of scripts.</title>
    <!--Requirejs first loads the module that is specified in data-main .. So it will load the module init,init has two dependencies first is knockout so it loads the knockout first, then myAppViewModel next -->
    <script type="text/javascript" data-main="scripts/init.js" src="scripts/require.js"></script>
</head>
<body>
    Name : <span data-bind="text: myName"></span>
</body>
</html>


init.js:
JavaScript
require(['knockout-3.2.0', 'myAppViewModel'], function(ko, myAppViewModel) {
    ko.applyBindings(new myAppViewModel());
});


myAppViewModel.js

JavaScript
define(function () {
    return function myAppViewModel() {
        this.myName = 'Sudheer';
    };
});


If i remove return from above code. It says myAppViewModel() is not a constructor. Why return is required in this context?
Posted

1 solution

It is beginning with new myAppViewModel part...new in JavaScript is looks like a keyword but actually an operator!!! As any operator also new has to return a value!
What actually new does is calling the function you gave him as parameter - and yes, this is a function even you like to think it as a class (in fact in JavaScript there is no difference more than semantics)...
In the normal JavaScript environment you would create myAppViewModel without the envelop that knockout.js requires, like this:
JavaScript
function myAppViewModel() {
  this.myName = 'Sudheer';
}

In this case new operator was able to create a new class out of the function without return too, but in knockout.js you enclose your function/class inside an other function/class (define it called) you have to explicitly return the correct answer to new...
That's the reason it will not work without return at the beginning...
 
Share this answer
 
Comments
[no name] 9-Dec-14 3:24am    
Thanq Peter. I got the context. Require assigns the return value of define function to myAppViewModel. According to knockout a module is a function so define function should return a function. If i remove return undefined is returned. So it says undefined is not a function.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900