I want to call API URL to get data, and pass it to a view, but encounter an error when using fetch property:
Uncaught TypeError: Cannot read property 'localStorage' of undefined
at G.d.Backbone.sync (backbone.localStorage-min.js:8)
at G.d.fetch (backbone-min.js:23)
at G.d.initialize (backbone:120)
at G.d.g.Collection (backbone-min.js:18)
at new G.d (backbone-min.js:38)
at backbone:137
The code:
var app = {};
app.postCollection = Backbone.Collection.extend({
url: 'https://jsonplaceholder.typicode.com/comments',
initialize: function(){
this.fetch({
success: this.fetchSuccess,
error: this.fetchError
});
},
fetchSuccess: function (collection, response) {
console.log('Collection fetch success', response.data);
/*console.log('Collection models: ', this.models);*/
},
fetchError: function (collection, response) {
throw new Error(" fetch error");
}
});
try {
app.postcollection = new app.postCollection();
}
catch (e) {
console.log(e.message);
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.0/backbone.localStorage-min.js" type="text/javascript"></script>
You are using an old version of localStorage. Update to a new version, for example https://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.1.16/backbone.localStorage.js
Also, you need to specify localStorage property on the collection like localStorage: new Backbone.LocalStorage("SomeCollection"),
Working JSFiddle
Related
I'm fetching comments from the reddit API and trying to update an array with $set so it can update the view, but I get this error:
Uncaught (in promise) TypeError: $set is not a function
VM component:
export default {
name: 'top-header',
components: {
Comment
},
data () {
return {
username: '',
comments: []
}
},
methods: {
fetchData: function(username){
var vm = this;
this.$http.get(`https://www.reddit.com/user/${username}/comments.json?jsonp=`)
.then(function(response){
response.body.data.children.forEach(function(item, idx){
vm.comments.$set(idx, item);
});
});
}
}
}
I've set up a codepen to demonstrate the two possibilities: http://codepen.io/tuelsch/pen/YNOqYR?editors=1010
The $set method is only available on the component itself:
.then(function(response){
// Overwrite comments array directly with new data
vm.$set(vm, 'comments', response.body.data.children);
});
or, since Vue.js sould be able to trace the push call on an array:
.then(function(response){
// Clear any previous comments
vm.comments = [];
// Push new comments
response.body.data.children.forEach(function(item){
vm.comments.push(item);
});
});
See https://v2.vuejs.org/v2/api/#vm-set for the API reference.
Alternatively, you can use the global Vue.set method with the same parameters:
import Vue from 'vue';
// ...
Vue.set(vm, 'comments', response.body.data.children);
See https://v2.vuejs.org/v2/api/#Vue-set for the global API reference.
What I'd like to do is get at the returned data from the LinkedIn API named data from the function named getProfileData. How can I access the data that contains the information such as firstName and lastName but in getProfileData and not just in the function onSuccess?
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: YOUR_API_KEY_HERE
authorize: true
onLoad: onLinkedInLoad
</script>
<script type="text/javascript">
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", getProfileData);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
IN.API.Raw("/people/~").result(onSuccess).error(onError);
// I want to see the profile data in here.
}
</script>
You must fix something in your code :
IN.API.Raw("/people/~:(id,first-name,last-name,location,positions)?format=json").result(onSuccess).error(onError);
I'm using a Router to organise my Backbone app. In my edit route I'm calling fetch on a model instance to get the model's data for the edit form:
App.Router = Backbone.Router.extend({
routes: {
"": "index",
"edit(/:id)": "edit"
},
index: function () {
_.bindAll(this, "getItemByID", "onModelFetchError", "showError");
},
edit: function (id) {
this.formEditItem = new App.Views.FormEditItem({model: this.getItemByID(id), parent: this});
},
getItemByID: function(id) {
var item = new App.Models.Item({id: id});
item.fetch({
success: function(model, response, options) {
console.log('Success');
return model;
},
error: this.onModelFetchError
})
},
onModelFetchError: function (model, response, options) {
this.showError(response.responseText);
},
showError: function(msg) {
this.error = new App.Views.Error({parent: this, message: msg});
}
});
The fetch call works fine, but I'm having trouble handling errors. I want to instantiate an Error view and display the message in it. But when I try this code, I get "Uncaught TypeError: Object [object global] has no method 'showError'". It seems that assigning onModelFetchError as the handler for fetch errors puts it in the global scope, even when I bind it to the Router with _.bindAll.
Is there any simple way to ensure onModelFetchError remains in the Router scope?
You are calling to _.bindAll() inside of the index function which is fired by the route "", so if you don't fire that route they'll never get bind to the context object. I would suggest to create an initialize method for your router so you can bind all the functions for any route inside of it.
initialize: function() {
_.bindAll(this, "getItemByID", "onModelFetchError", "showError");
}
Try with
getItemByID: function(id) {
var item = new App.Models.Item({id: id});
var self = this; // this changed
item.fetch({
success: function(model, response, options) {
console.log('Success');
return model;
},
error: self.onModelFetchError // this changed
})
},
So i have a problem whereby I have a backbone collection that am using to create function to save data to a REST API. The data is saved to the server and a model is added to the current collection but then the add event for the collection is not fired.Below are snippets of the code
The views initialize function
intialize : function() {
this.listenTo(this.collection, 'add', this.updateList);
},
The updateList function only does a console log.The views function that saves data using the collection is:
cards = this.collection;
debugger
cards.create(data, {
success : function(model, response) {
console.log("success on saving card");
console.log(response);
console.log("Updating list");
console.log(cards);
},
error : function(model, response) {
console.log("error on saving card");
console.log(model);
console.log("response");
console.log(response);
}
})
return false;
Try this code in your view:
initialize: function() {
this.collection.on('add', this.updateList, this);
}
Or:
var someCollection = new SomeCollection();
var view = new SomeView({collection: someCollection});
view.listenTo(someCollection, 'add', view.updateList);
why don't you just use: this.model.on('change', doAction, this); inside the view? if I understood correctly, this is a better solution since your model is changing.
plus, I couldn't find anywhere a place where the ListenTo() is mandatory over the On() function, can you tell me where you saw it?
I am a beginner to javascript and stackmob.
How can I fetch data from stackmob for my webpage(dashboard) using javascript?
I was also trying to update data but i was unsuccessful.
Here is my code for updating the value of 'done' from 'false' to 'true' :
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://static.stackmob.com/js/stackmob-js-0.9.1-bundled-min.js"></script>
</head>
<body>
<script type="text/javascript">
StackMob.init({publicKey: "my_key",apiVersion: 0});
</script>
<script type="text/javascript">
var newtask = new task({ newtask_id: 'my_id_primarykey' });
newtask.save({done:true},{
success: function(model, result, options) {
console.debug(model.toJSON());}
error: function(model, result, options) {}});
</script>
<!-- rest of the code -->
</body>
I need to be able to create an instance(that i have been able to do), update values, delete values and fetch values.
I am not able to update and save multiple values of an existing instance to stackMob.
StackMob.init({publicKey:"mykey",apiVersion:0});
var Task=StackMob.Model.extend({schemaName:'taskdevice'});
var task1=new Task({task_device_id:'my_id'});
task1.save({imei:'112',name:document.getElementById('e2').value),dob:(document.getElementById('e3').value),email:(document.getElementById('e4').value),phone:(document.getElementById('e5').value)},{
success: function(model, result, options) {
alert("success");
console.debug(model.toJSON());},
error: function(model, error, options) {alert("Failure");}
});
It is failing everytime if i try to update multiple values.
You had a few syntax errors in your code there such as the comma between your success and error callbacks. Also, you need to define your Model before trying to save/read data. Your task variable wasn't defined. So you extend the Model to define what schema it should be related to.
Here's a jsFiddle with a working example: http://jsfiddle.net/wyne/eATur/
You should also check out the JavaScript Developer Guide on StackMob's developer center.
// Initialize StackMob object with your public key
StackMob.init({
publicKey: "api_key", apiVersion: 0
});
// Define Model and associate it with a Schema
var Task = StackMob.Model.extend({ schemaName: 'task' });
$(document).ready(function () {
// Create new instance of the Model with id of object to update
var updateTask = new Task({ "task_id": "INSERT_OBJECT_ID" });
// Update the task with done=false and save it to StackMob
updateTask.save({ done: true }, {
success: function(model, result, options) {
console.log( "Updated object!" );
console.log( model.toJSON() );
},
error: function(model, error, options) {
console.log( "Error updating" );
}
});
});