Converting Backbone.js App to communicate with parse.com - javascript

I am an IT student and I'm learning how to use Backbone.js. I read all the documentation but I find it easier to learn when I use example apps,because I never have been programming this type of apps,so it was hard and confusing to think of a way to build my own app, so I used https://github.com/dperrymorrow/example-backbone-app to make similar edited app. The example app doesn't have a server side.
Now I need to connect the app to use parse.com as a backend(server-side) instead to use local collection.
If someone could please tell me what should I change and transform in the code so it connects example app to parse.com app with REST API so when I edit something in the app to be syncronized with parse.com.
I will be really grateful if someone is willing to explain this in a more descriptive way than saying :"you should read documentatin" because I did,and I still don't get the point :)
Have a nice day.

It's just about having the right backbone models and collections and settings the right url on the collection and urlRoot on the model. Then you can just can just call backbone methods like sync, save or delete.
Best detailled answer covering also the REST explanation probably is this one.

Cant you just swap the backbone collection and model to Parse's ones?
Parse.com is a webservice providing REST interfaces for anything you like, Lets connect that to our Backbone models.
First of all Lets create a new app on Parse.com, mine is called FunkyAppartments.
Insert the script tag for loading Parse javascript lib into index.html or whathever:
<script src="http://www.parsecdn.com/js/parse-1.5.0.min.js"></script>
Switch the backbone model and collection to use parse types instead (and rename the fetch method if you have extended backbones, since we do not want to overide the one of parse):
//var Appartment = Backbone.Model.extend(); Backbone wo. Parse.com
var Appartment = Parse.Object.extend("Appartment");
//var Appartments = Backbone.Collection.extend({ Backbone wo. Parse.com
var Appartments = Parse.Collection.extend({
model: Appartment,
initializeData: function(){
var self = this;
var callback = function (data){console.log(data); self.reset(data)};
S.Appartments.loadAppartments(callback);
},
loadAppartments: function(callback){
debugger;
this.query = new Parse.Query(Appartment);
var result = this.fetch();
callback(result);
return result;
}
});
I added a debugger tag in the load appartments so that developer tools breaks in the middle of the controller, here I have access to the Appartment private type of the controller, hence i can store some data on the parse server and verify by pasting the below in the developer tools console.
var testAppartment = new Appartment();
testAppartment.save({name: "foobars"}).then(function(object) {
alert("yay! it worked");
});
Yei, the data shows up in the parse.com UI for the app we just added there. And more importantly it shows up in our frontend. That was easy!

Related

How to get data from back end side, to use it in the browser side?

I am new to programming, and I heard that some guys on this website are quite angry, but please don't be. I am creating one web app, that has a web page and also makes som ecalculations and works with database (NeDB). I have an index.js
const selects = document.getElementsByClassName("sel");
const arr = ["Yura", "Nairi", "Mher", "Hayko"];
for (let el in selects) {
for (let key in arr) {
selects[el].innerHTML += `<option>${arr[key]}</option>`;
}
}
I have a function which fills the select elements with data from an array.
In other file named: getData.js:
var Datastore = require("nedb");
var users = new Datastore({ filename: "players" });
users.loadDatabase();
const names = [];
users.find({}, function (err, doc) {
for (let key in doc) {
names.push(doc[key].name);
}
});
I have some code that gets data from db and puts it in array. And I need that data to use in the index.js mentioned above, but the problem is that I don't know how to tranfer the data from getData.js to index.js. I have tried module.exports but it is not working, the browser console says that it can't recognize require keyword, I also can't get data directly in index.js because the browse can't recognize the code related to database.
You need to provide a server, which is connected to the Database.
Browser -> Server -> DB
Browser -> Server: Server provides endpoints where the Browser(Client) can fetch data from. https://expressjs.com/en/starter/hello-world.html
Server -> DB: gets the Data out of the Database and can do whatever it want with it. In your case the Data should get provided to the Client.
TODOs
Step 1: set up a server. For example with express.js (google it)
Step 2: learn how to fetch Data from the Browser(Client) AJAX GET are the keywords to google.
Step 3: setup a Database connection from you Server and get your data
Step 4: Do whatever you want with your data.
At first I thought it is a simple method, but them I researched a little bit and realized that I didn't have enough information about how it really works. Now I solved the problem, using promises and templete engine ejs. Thank you all for your time. I appreciate your help)

How to perform Twitter API search in Node.js with user-entered keyword

I am a complete newbie to Node.js, Express, and Angular. I have a Node/Express app running on my localhost. I am trying to make this into a Twitter search application, using the Twitter API, so that I can enter a search term and the API returns the search results for this search term. For this, I am using the twitter package. In index.js, I have filled in my Twitter keys and secrets at the Xs as follows:
var Twitter = require('twitter');
var client = new Twitter({
consumer_key: 'X',
consumer_secret: 'X',
access_token_key: 'X',
access_token_secret: 'X'
});
When I then put the following code into index.js, the search results for keyword "awesome" are logged to the console:
var tmpSearch = 'awesome';
client.get('search/tweets', {q: tmpSearch}, function(error, tweets, response){
if (error) throw error;
console.log(tweets);
});
This works. My home page uses a controller myCtrl, which makes sure that when the user presses the Search button (with property ng-click="search(searchTerm)"), the entered search term is assigned to the variable searchTerm (using ng-model="searchTerm" for the input area). The code for the controller is as follows:
app.controller('myCtrl', ['$scope',
function($scope){
$scope.search = function(searchTerm){
console.log("Searching for " + searchTerm);
// Search here...
console.log("Search finished.");
};
}
]);
It logs the search term to the console, but I don't know how to proceed from here. Where it says // Search here... I want to execute the client.get code from above, but I cannot use the client variable from routes/index.js in my public/javascript.js. What do I need to add to my code in order to perform the search?
I have the feeling that I am not understanding a very important part of Node/Express, but I don't know which part that is, so my search for solutions hasn't been very succesful. I have never used APIs before either, and I have spent many hours going through documentation and tutorials both for Node.js and for the Twitter API, but it's only a week ago that I started learning it so most of it isn't making a lot of sense to me yet. I have found a few examples of Node apps using the Twitter API on GitHub (most of them using different packages), of which I tried to understand the code, but I couldn't figure out what I should do. I hope someone will be patient enough to explain to me what I am missing.
You need to think about where each step is happening. The Twitter code you're showing is running in Node, on your server. The myCtrl code is AngularJS code, running in the browser. As you've sensed, there's something missing to connect them.
The flow of control will be like this:
user types in a term and clicks the Search button
your controller sends an HTTP request to your Node.js
your Node.js server makes a call to Twitter
Node.js hands the results back to the client (myCtrl)
the results are displayed to your user
You have pieces of this in place. What's missing is the HTTP request and response. Here's what you do:
add an endpoint, say, /api/twittersearch. You'll do this with Node.js and Express
the implementation of that endpoint will be a function with parameters req and res (request and response; those names are not required but are frequently used); this function will do the new Twitter and client.get code that you have above
the client.get call has a callback function, which you have currently implemented; in your callback, you'll send the tweets back to the client (something like res.send(tweets)
in your controller, your "search here" code will be something like $http.get('/api/twittersearch?term=' + searchTerm)
That last call to $http.get() returns a Promise. You'll follow that up with .then(function(tweets){ ... }).catch(function(errors){ ... }). In the function you pass to then, you'll take the results from your call and update your model.

Meteor: Creating URLs for sharing (currently using iron-router)

I have a meteor app that uses iron-router.
How do I make this meteor app create a fixed URL for sharing?
For example in jsfiddle.net, you start of in just jsfiddle.net PLAINLY.
However, after you type in the code, etc...and you decide you wanna share this with the world, you click on save. After you click on save, the link above changes to something like: jsfiddle.net/m9mfLn3p/.
And now you can use jsfiddle.net/m9mfLn3p/ to share that page with that certain setting with the world....
How do I achieve something similar in my meteor app that uses iron-router?
Thank you very much.
I have a similar pattern in my app. To solve this problem I have a collection that contains the data context that will be used by the route. Then I just create a document with the required data and use the _id of the document in that collection to create a url that can be reused.
Ex:
var id = Permalinks.insert(object); // object is the data I'll need later
var url = Meteor.absoluteUrl() + "myPath/" + id;
... share this url however - email, SMS, etc...
Then a route:
Router.route("/myPath/:id",{
data: function(){
return Permalinks.findOne({ _id: this.params.id });
}
});

Log client browse website information in backbone.js

I'm using this code to get client information :
$.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?",function (data) {
console.log(data.geoplugin_request);
console.log(data.geoplugin_countryName);
});
Then I would like to record this information at the first time that client visit the website (session start of the website). My current project are using backbone.js, require.js, underscore.js.
Any suggestions would be appreciated. Thanks.
Assuming that you have application.js file which act as a entry point of the backbone aplication which initializes your router an all stuff, you can set the client details in the browser using localStorage.
// Retrieve the object from storage
var retrievedVar = localStorage.getItem('countryName');
if( retrievedVar == null) {
$.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?",function (data) {
console.log(data.geoplugin_countryName);
// Put the object into storage
localStorage.seItem('countryName', JSON.stringify(data.geoplugin_countryName)
});
Hence the getJSON will only be fired once when localStorage var is not set.

Backbone.js in an offline application

I am using Titanium to build a desktop app using web technologies. I decided to use Backbone.js as my mvc. The problem is the application runs not on a server. This is my Backbone model and collection:
window.Student = Backbone.Model.extend({
initialize: function(){
this.bind("save", this.value_change);
},
value_change: function(){
alert("Student model saved for : " + this.attributes.first_name);
},
urlRoot : http://localhost:8080/student/,
});
window.Students = Backbone.Collection.extend({
model: Student,
url: 'http://localhost:8080/students/',
});
and try fetching the values from the server using
var students = new Students
students.fetch()
I get this error:
message: "'undefined' is not an object (evaluating '$.ajax')"
I am assuming this has to do with the url part. It is not able to fetch the values from the server. Any Ideas?
The problem is backbone saves models on a server. It does this by sending ajax requests to your server. What you want to do is overwrite the persistence mechanism
Use backbone.localStorage to save state in localStorage rather then a database
collection.fetch() will fire a reset event on the collection, and not a save event. Save is a Model method to execute a POST request to your server, when you want to persist your instance model on your server.
You should try this instead :
window.Student = Backbone.Model.extend({
});
window.Students = Backbone.Collection.extend({
model: Student,
url: 'http://localhost:8080/students/',
initialize: function(){
this.bind("reset", this.value_change);
},
value_change: function(){
alert("Students fetched ");
},
});
var students = new Students();
students.fetch();
I'm not sure what you mean when you say
The problem is the application runs not on a server
But if your javascript does not run on the same domain as your server, you may have some cross domain javascript issues... Here is post with an exemple using Ruby on Rails : http://www.tsheffler.com/blog/?p=428
Thanks for all your answers. The problem laid in loading jquery after backbone. I loaded jquery first and it worked out fine. Thanks to parshap from the irc of #documentcloud.
Try https://github.com/Ask11/backbone.offline
Allows your Backbone.js app to work offline

Categories