0

I am creating a module with dojo. This module is about configuration.

define(["geometry/Point"], function (Point) {
        var sp = new Point(122, -142);
        return {            
            startPoint: new Point(122, -142),
            globalOptions: {
                logo: false,
                center: sp
            },

        };
    })

In this module, if I use sp varible as center, code is working. But if I use center as start point, the center is coming null. Like following

define(["geometry/Point"], function (Point) {
        return {            
            startPoint: new Point(122, -142),
            globalOptions: {
                logo: false,
                center: this.startPoint
            },

        };
    })

I deleted the varible sp and used this.startPoint but center is coming null.

infused
  • 24,000
  • 13
  • 68
  • 78
barteloma
  • 6,403
  • 14
  • 79
  • 173
  • And what is your question? You cannot reference properties of the object during definition. – Felix Kling Sep 12 '13 at 08:07
  • possible duplicate of [Self-references in object literal declarations](http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – Felix Kling Sep 12 '13 at 08:09

4 Answers4

2

That's because you're referencing the wrong object. If you use this at the center property, you're actually not referencing to your module anymore. Because you're instantiating a new object, it will actually refer to the global object, which is (if you're using a browser) window.

Your first solution works because sp is scoped so that it can be accessed from your module as well as from your globalOptions property.


EDIT (as requested from the comments):

To declare a module to access its functions you should use:

define(["dojo/_base/declare", "dojo/_base/lang", "dojo/_base/array"], function(declare, lang, array) {
    return declare(null, {
        param: ["a", "b", "c"],
        action: function() {
            this.otherAction(); // Call other action
        },
        otherAction: function() {
            array.forEach(this.param, lang.hitch(this, "lastFunction"));
        },
        lastFunction: function(item, idx) {
            console.log(idx + " " + item);
        }
    });
});

This example shows some basics in Dojo. To create a module you should use dojo/_base/declare. The first parameter null is to define a list of inherited modules, in this case none.

Parameters and functions can be declared in a similar way. Calling a function from another function should be done by providing the context this, for example this.otherAction().

If you lose the this context, you can use lang.hitch(). It in fact calls the function, but preserves the context. That's what I do with lang.hitch(this, "lastFunction").

I can explain it even more, but I think it would be useful to read this tutorial.

g00glen00b
  • 41,995
  • 13
  • 95
  • 133
1

Are you trying to do somthing like this,

define(["geometry/Point"], function (Point) {
        return {            
            startPoint: new Point(122, -142),
            globalOptions: {},

            postCreate: function () {
            this.globalOptions = {
            logo: false,
            center: this.startPoint
            }

          }    
        };
    })

this issue occurs because of scope of this..

hope this will help you..

Vikash Pandey
  • 5,407
  • 6
  • 41
  • 42
  • This probably won't work since you're not inheriting from anything. `postCreate` is not a default function, but it's actually a hook defined by `dijit/_WidgetBase`. – g00glen00b Sep 12 '13 at 08:23
  • @DimitriM thanks, i know we need to inherit base widget or base class for this.. and this was only a sample so i didn,t go to the deep.. – Vikash Pandey Sep 12 '13 at 08:26
  • I was only mentioning it for other people who would use this code and notice that `globalOptions` isn't initialized. ;) But what would you do if this module isn't a widget. As far as I see, `geometry/Point` has no intent to be a widget, so inheriting `_WidgetBase` would not suffit. – g00glen00b Sep 12 '13 at 08:58
  • Have you any suggestion to Access functions of a modüle? How can I declare it? – barteloma Sep 12 '13 at 13:41
  • @youtubeline, for accessing a function this may be helpfull... http://stackoverflow.com/questions/5126407/javascript-modular-layout-how-to-call-a-function-defined-in-one-module-from-an – Vikash Pandey Sep 13 '13 at 04:36
  • for module detail structure i have added an answere below.. lets see if that is helpfull for you.... otherwise feel free to shoot your queries:) – Vikash Pandey Sep 13 '13 at 04:39
1

Modules

The two key concepts you need to be aware of here are the idea of a define method for facilitating module definition and a require method for handling dependency loading. define is used to define named or unnamed modules based on the proposal using the following signature:

    define(
    module_id /*optional*/,
    [dependencies] /*optional*/,
    definition function /*function for instantiating the module or object*/
    );

As you can tell by the inline comments, the module_id is an optional argument which is typically only required when non-AMD concatenation tools are being used (there may be some other edge cases where it's useful too). When this argument is left out, we call the module anonymous.

When working with anonymous modules, the idea of a module's identity is DRY, making it trivial to avoid duplication of filenames and code. Because the code is more portable, it can be easily moved to other locations (or around the file-system) without needing to alter the code itself or change its ID. The module_id is equivalent to folder paths in simple packages and when not used in packages. Developers can also run the same code on multiple environments just by using an AMD optimizer that works with a CommonJS environment such as r.js.

Back to the define signature, the dependencies argument represents an array of dependencies which are required by the module you are defining and the third argument ('definition function') is a function that's executed to instantiate your module. A barebone module could be defined as follows:

// A module_id (myModule) is used here for demonstration purposes only

define('myModule',
['foo', 'bar'],
// module definition function
// dependencies (foo and bar) are mapped to function parameters
function ( foo, bar ) {
// return a value that defines the module export
// (i.e the functionality we want to expose for consumption)
// create your module here
var myModule = {
doStuff:function(){
console.log('Yay! Stuff');
}
}

return myModule;
});

// An alternative example could be..
define('myModule',
['math', 'graph'],
function ( math, graph ) {

// Note that this is a slightly different pattern
// With AMD, it's possible to define modules in a few
// different ways due as it's relatively flexible with
// certain aspects of the syntax
return {
plot: function(x, y){
return graph.drawPie(math.randomGrid(x,y));
}
}
};
});

require on the other hand is typically used to load code in a top-level JavaScript file or within a module should you wish to dynamically fetch dependencies.

// Consider 'foo' and 'bar' are two external modules
// In this example, the 'exports' from the two modules loaded are passed as
// function arguments to the callback (foo and bar)
// so that they can similarly be accessed

require(['foo', 'bar'], function ( foo, bar ) {
// rest of your code here
foo.doSomething();
});

hoping this is helpfull for you...

Vikash Pandey
  • 5,407
  • 6
  • 41
  • 42
0

Your first approach was the correct one, but you had a bit of duplication that you didn't need in the startPoint definition:

function test() {

    var startPoint = "x,y"

    return {            
        startPoint: startPoint,            
        globalOptions: {
            logo: false,
            center: startPoint
        }
    };
}

console.log(test().startPoint)
console.log(test().globalOptions)

Test in JSBIN: http://jsbin.com/IxENEkA/1/edit

bitoiu
  • 6,893
  • 5
  • 38
  • 60