Sharing object instances in requirejs

I define a module Fooand create it in another module Bar. I have a third module Otherthat I would like to provide with the same instance Foothat was Barcreated and modified.

define('Foo', [], function() {
    var test = function() {
        this.foo = 'foo';        
    };

    return test;
});

define('Bar', ['Foo'], function(Foo) {
    Foo = new Foo();
    Foo.bar = 'bar';
    console.log('From bar', Foo);
});

define('Other', ['Foo'], function(Foo) {
    console.log('From the other', Foo);
});


require(['Foo', 'Bar', 'Other'], function(Foo, Bar, Other) {
    console.log('Bringing it all together');
});

http://jsfiddle.net/radu/Zhyx9/

Without a requirement, I would do something like:

App = {};

App.Foo = function() {
    this.foo = 'foo';
}

App.Bar = function() {
    App.Foo = new App.Foo();
    App.Foo.bar = 'bar';
    console.log('From bar', App.Foo);
}

App.Other = function() {
   console.log('From other', App.Foo);
}

App.Bar();
App.Other();

http://jsfiddle.net/radu/eqxaA/

I know that I am missing something here, and since this is one of my first raids in requirejs, there may be some misunderstanding. The example may look tricky, but I come across something similar in a shoehorning project in using Backbone and RequireJS.

+5
source share
3 answers

, , :

define('Foo', [], function() {
    var test = function() {
        this.foo = 'foo';        
    };

    return new test();
});

define('Bar', ['Foo'], function(Foo) {
    Foo.bar = 'bar';
    console.log('From bar', Foo);
});

define('Other', ['Foo'], function(Foo) {
    Foo.other = 'other';
    console.log('From the other', Foo);
});


require(['Foo', 'Bar', 'Other'], function(Foo, Bar, Other) {
    console.log('Bringing it all together');
});

http://jsfiddle.net/radu/XEL6S/

, , , Foo , , DOM . , RequireJS, , . , Foo, , domReady, requireJS.

+1

, return, ,

,

define('Bar', ['Foo'], function(Foo) {
    Foo = new Foo();
    Foo.bar = 'bar';

    //return instantiated Foo
    return Foo;
});


require(['Foo', 'Bar', 'Other'], function(Foo, Bar, Other) {
    //Bar is the instantiated Foo, exposed from Bar
    console.log(Bar);
});
+3

- , api. console.log .

- :

define('Bar', ['Foo'], function(Foo) {
    var Bar = { my: 'bar'};
    //or maybe return a function or whatever 
    return Bar;
 });
+1

All Articles