문제

I have a Meteor project that is starting to get out of hand with about 800 lines of code. I set out today to modularize and clean things up a bit and things are looking good, but I'm getting some errors that I don't know the best way how to deal with.

Here's a prime example.

I am using d3 to create a force layout (this question isnt specific to d3). I instantiate some variables and most notably

var force = d3.layout.force()

in a file

/client/views/force/forceLayout.js

I made a bunch of controls for this force layout and put them in their own .html and .js files. Heres an example

initChargeSlider = function() {
    d3.select("#charge-slider")
        .call(d3.slider()
            .min(-301)
            .max(-1)
            .step(5)
            .value(Session.get("charge"))
            .on("slide", function(evt, value) {
                Session.set("charge", value);
                // force.stop();
                force = force.charge(value);
                force.start();
            }));
}

Template.charge.rendered = function() {
    initChargeSlider();
};

in file

/client/views/force/controls/sliders/charge.js

Due to Meteor loading deeper directories first, I get an error at force = force.charge(value) because forceLayout.js hasn't instantiated force yet.

I'm curious what is the most best way of dealing with this. Moving the files around and loading order is just reversing all the modularizing I just did. I think a singleton or an object or monad may be in order but I'm not sure which or why. I would appreciate an explanation of how to go about fixing these errors.

Thanks

Chet

도움이 되었습니까?

해결책

Meteor before 0.6.5 run files without wrapping them inside a function wrapper (function() { /* your code */ })().

This behavior is still followed if you place your files in client/compatibility folder:

Some JavaScript libraries only work when placed in the client/compatibility subdirectory. Files in this directory are executed without being wrapped in a new variable scope. This means that each top-level var defines a global variable. In addition, these files are executed before other client-side JavaScript files.

Now, Meteor is more unforgiving of global variables and now one needs to be explicit about declaring them. Hence,

window.force = d3.layout.force()

or even

this.force = d3.layout.force(); // this === window in global context.

would solve the problem.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top