简体   繁体   中英

Meteor function define across all .js project files

Say I have a function that returns a specific id of a player in a client side java-script file:

var playerId = function () {
    return Player.findOne({current:true})._id;
};

However as the project has grown, I have started to break up my code into a variety of .js files (player.js, game.js, round.js, etc).The problem arises when I want to reuse the function. I cannot call the playerId() function from a different .js file. As of right now I am just copying and pasting the function into every .js file that utilizes it. Is there a place I can define the function so that it is available to every .js file?

The correct answer is simply to remove the var in the declaration statement of the variable you wish to export. http://docs.meteor.com/#namespacing

Also, make sure the load order is correct by following these rules : http://docs.meteor.com/#structuringyourapp

You can call the function by using the name of its .js in another file

Ex:

player.js

var player = {
 init: function() {
       player.playerId();
 },
 playerId : function () {
        return Player.findOne({current:true})._id;
 }
}
$(document).ready(function () {
        player.init();
});

game.js

game: function(){
      var p = player.playerId()
}

Besides giving the obvious tip of fixing your file dependencies, the best suggestion I can give is to use an excellent library called Require JS . This will not only automatically take care of file dependency order and downloads, but it will also keep your global-scope clean of these type of utility functions. Require will also force you into better programming habits, which is why I advocate learning/using require to solve your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM