I've been working on a small Spotify app for some time now. I started using the old API (0.x) but now that I want to access the user's playlists, I need to use the library module which is only available throught the API version 1.0
The spotify team even gives a migration guide to do so ! (if you read me: Thanks guys for all this ;) ).
I already have created a few objects (It's a small app so I don't need much more than that), with a function for each one of my needs, like so:
var sp = getSpotifyApi();
var models = require('sp://import/scripts/api/models');
var player = models.player;
var views = require('sp://import/scripts/api/views');
// in file 'mySpotify.js'
var mySpotify =
{
playerNextTrack: function()
{
player.next();
},
}
Whenever I need to Skip the current track, I can call mySpotify.playerNextTrack();
But now, with the new API, I need to do things like this (from Spotify doc):
require(['$api/models'], function(models) {
var player = models.player;
player.next();
});
My question is simple: how can I include this kind of code into my objects ? How can I give a name to this last "function" ?
As I'm fresh new to JS, I'm probably doing something wrong or understood something the wrong way so feel free to elaborate if you can ;)
I'll start with what I think is the easy answer, just put the require([], function {[all your code]}); around your whole myspotify.js file. That's basically what I have for mine, though I haven't built any of my own objects. Don't think that would matter.
Update
Here's a bit more info showing that objects can be used. Is this what you were looking for?
require(['$api/models'], function(models) {
var mySpotify =
{
playerNextTrack: function()
{
models.player.skipToNextTrack();
},
}
var playtest = document.querySelector('#playtest');
playtest.addEventListener('click', function() { mySpotify.playerNextTrack(); });
});
Related
In Screeps, I this code doesn't work:
var sources = creep.room.find(Game.FIND_SOURCES_ACTIVE);
It says this:
Cannot read property 'find' of undefined
I have been looking around and cannot find ANY other way to find sources.
Also I've noticed that most of other peoples code doesn't work and even the tutorial's code no longer works when put into the real game.
I can't be completely sure about your issue since I don't have your complete code to go off of but one issue could be that creepis not defined.
You need somewhere in your code to define creep such as a for loop to loop over each of your creeps in the game or room.
var roleMiner = require('role.miner') // role.miner being the module name for miner actions
for(var name in Game.creeps) {
var creep = Game.creeps[name];
//
// do whatever you wish with the current selected creep.
//
// most of the time you will call a module similar to what the tutorials suggest and put your actions for it in there
//
if(creep.memory.role == 'miner'){
roleMiner.run(creep); // passes the current selected creep to the run function in the module
}
}
So, in your roleMiner module you would have something that defines your miners actions.
var roleMiner = {
run: function(creep) {
// this one returns an array of the sources that are in the room with the creep
var sourcesRoom = creep.room.find(FIND_SOURCES);
// this one returns the source object which is closest to the creeps positon
var sourcesClose = creep.pos.findClosestByRange(FIND_SOURCES);
}
}
module.exports = roleMiner;
Hope this helps.
Screeps have some ... mechanism when sharing your data between each game tick.
If you store any thing in global Memory object, your data will lose all its prototype.
to restore your prototype use Object.setPrototypeOf(creep,Creep.prototype) or create new Creep object from your creep id.
I think what you are looking for is:
var sources = creep.pos.findClosestByRange(Game.SOURCES);
or
var sources = creep.pos.findClosestByPath(Game.SOURCES);
im a new player, not sure my code is efficient, i think the find method will be like this:
var sources = creep.room.find(FIND_SOURCES_ACTIVE)
creep will going to the active resource to harvester.
I have an application where users can follow other users. I want to have a real-time update system, display the total count of followers a user has.
I've just started playing around with Firebase and Pusher, but I don't understand one thing - will each user have their own 'channel'? How would I handle such thing as a follower counter update?
I followed the tutorial and saw that push method can create lists, so one solution I can see is having a list of all the users, each user being an object something like this:
{ username: 'john_doe', follower_count: 6 }
But I don't understand how would I actually track it on the front end? Should I have a filter, something like this?
var user = users.filter(function(user) { return user.username === 'john_doe'; });
// code to display user.follower_count
Or is there a different way that I'm missing?
Most of Firebase logic is based on listeners, you can add a listener to events happening in your collections and when those events happen, you do something.
One way to go about this would be:
var myFollowerListRef = new Firebase(PATH_TO_YOUR_COLLECTION);
myFollowerListRef.on("value", function(snapshot) {
console.log(snapshot.length);
});
This way, every time your follower collection changes, the asynchronous function fires and you can do what you want with the fresh data.
For more information:
https://www.firebase.com/docs/web/guide/retrieving-data.html
Hope this helps, I'm still a beginner in Firebase.
#Th0rndike's approach is the simplest and works fine for relatively short lists. For longer lists, consider using a transaction. From the Firebase documentation on saving transactional data:
var upvotesRef = new Firebase('https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes');
upvotesRef.transaction(function (current_value) {
return (current_value || 0) + 1;
});
But I recommend that you read the entire Firebase guide. It contains solutions for a lot of common use-cases.
I am writing a Javascript web app using Firebase. If I have data like this in my JSON tree:
users
session1
screenname:Bill
session2
screenname:Steve
...and I know the session number, how can I grab the "name" of the user? I have tried this:
valUsers.child('session1').child('screenname').once('value', function(data){
console.log(data);
});
But that does not seem to work. I'm guessing I have a syntax issue?
You were pretty close, but needed to use DataSnapshot.val() as shown below to access the point you want.
var ref = new Firebase('yourfirebaselocation/users');
var sessionNum = 'session1';
ref.child(sessionNum + '/screenname').once('value', function(dataSnapshot) {
var specificScreenname = specificPoint.val();
}
When working with Firebase, you may want to also explore working with Promise objects. This would allow you to create some repeatable functions that can reuse your reference on multiple locations and also give Firebase time to respond to your query.
var ref = new Firebase('yourfirebaselocation/users');
function getUser(theRef, location) {
return new Promise(
function(resolve, reject) {
theRef.child(location).once('value', function(dataSnapshot) {
resolve(dataSnapshot);
});
});
}
getUser(ref, specificlocationvariable).then( function(val) {
specificScreenname = val.val();
});
You don't specify other than 'JavaScript' so do keep in mind that Promises are an ECMAScript 6 proposal with some compatibility issues, but a lot of the JS frameworks have an implementation for it that smooth that issue (Angular, Ember, etc).
Not sure if I'm going about this the right way. I'll map out what I'm trying to achieve and please give me any feedback you can. Also very new to meteor so sorry if I'm a bit uneducated in some aspects. This is going to be a two player game where users login in with accounts-twitter or accounts-facebook. Here's the tricky part it will only initialize the game if there are two users logged in. To figure out who is logged in I have put this line of code in my server portion:
if (Meteor.isServer) {
Meteor.publish("userStatus", function() {
return Meteor.users.find({
"status.online": true
})
});
}
My idea of what needs to be done is write an if statement if(userStatus === true){get a users "_id"} then push that user into an array and have a for loop run through every 2 users signed on in the array and initialize a game for them. Also the main question is how do I grab the users ID if status.online is true? Also any input on how to make this more efficient is much appreciated.
Answering your "main question," you would do this with a mongoDB for-each like so.
Meteor.methods({
getOnline : function(){
var retArr = new Array();
Meteor.users.find({"status.online": true}).forEach(function(u){
retArr.push(u._id); //populated retArr with the id of users online
});
return retArr;
}
});
If I left out something or you need clarification on something, please comment.
I am trying to create a webapp on a node/couchdb/windows stack but get terribly stung by what seems to be a lack of experience.
In the database, there is a view that returns all users with passwords. Based on the tutorial for a blog I have tried to access the view through my node code.
Whenever I investigate the structure of the users or users variable, I get an undefined object.
The call to getDatabase() has been tested elsewhere and works at least for creating new documents.
function GetUser(login)
{
var users = GetUsers();
return users[login];
}
function GetUsers() {
var db = getDatabase();
var usersByEmail = [];
db.view("accounts", "password_by_email")
.then(function (resp) {
resp.rows.forEach(function (x) { usersByEmail[x.key] = x.value});
});
//usersByEmail['test'] = 'test';
return usersByEmail;
}
I am aware that both the use of non-hashed passwords as well as reading all users from the database is prohibitive in the final product - just in case anyone wanted to comment on that.
In case something is wrong with the way I access the view: I am using a design document called '_design/accounts' with the view name 'password_by_email'.
Your call to db.view is asynchronous, so when you hit return usersByEmail the object hasn't yet been populated. You simply can't return values from async code; you need to have it make a callback that will execute the code that relies on the result.