Backbone Model/Collection fetch does not store the result - backbone.js

its me again with another interesting Backbone.js question.
When I call Model#fetch() or Collection#fetch() then Backbone will call the server correct, but it will not store the result, but save works as intended.
In every tutorial I found they explain it that the model will be stored after fetch().
example
response contains 'success' and collection contains the XHR object with the correct json
tagCollection = new CategoryCollection();
tagCollection.fetch({
complete: function(collection, response) {
console.log(tagCollection.models);
},
});
code
/models/category.js
define(['underscore', 'backbone'], function(_, Backbone){
var CategoryModel = Backbone.Model.extend({
urlRoot: '/api/v1/category',
});
return CategoryModel
});
/collections/category.js
define(['underscore', 'backbone', 'categoryModel'], function(_, Backbone, CategoryModel){
var CategoryCollection = Backbone.Collection.extend({
model: CategoryModel,
url: '/api/v1/category'
});
return CategoryCollection
});
/api/v1/category(.json)
[
{
id: "1",
name: "Allgemeines",
deleted_at: null,
created_at: "2014-02-23 17:22:22",
updated_at: "2014-02-23 17:22:22"
}
]

Fetch accepts a 'success' callback rather than a 'complete' one. Assuming the data is coming backbone successfully from the server it's probably just not logging out because the callback isn't firing. Try this:
tagCollection.fetch({
success: function(collection, response) {
console.log(tagCollection.toJSON());
},
});

Related

Backbone fetch single model attributes

im trying to fetch a single Models attributes. I use this model as kind of a config file for an app im currently building. But i cant get my head around how to get the attributes in a nice way.
The model looks like this:
WelcomeModel = Backbone.Model.extend({
url: "assets/json/config.json",
parse: function (response) {
return response.data;
}
});
The json looks liks this:
{
"data": [{
"companyName": "lorem ipsum",
"companyLogo": "loremipsum.png"
}]
}
And in my view i fetch it like this.
this.model = new WelcomeModel();
this.model.fetch({
success: function(model,response) {
console.log(model);
},
error: function() {
console.log('error')
}
});
1) parse method returns array instead object. Replace
return response.data
with
return response.data[0];
2) add defaults hash to your WelcomeModel model.
defaults: {
companyName: '',
companyLogo: ''
}

how to post array by store of sencha

I create one store and init it with some params with one array.when I execute the load function, the array parameter becomes a string '[object object]'
the code as follows:
store:
Ext.define('test.store.info',{
extend: 'Ext.data.Store',
config:{
model:'test.model.info',
proxy:{
type:'ajax',
url:'http://domain/path',
actionMethods:'POST'
}
}
});
model:
Ext.define('test.model.info',{
extend:'Ext.data.Model',
config:{
fields:[
'code',
'data'
]
}
})
use in controller:
var store = Ext.getStore('info');
params = {
t1:[{
f1:'aa'
},{
f2:'bb'
}],
t2:'ddd'
}
console.log(params)
store.load({
params:params
});
or I just use Ajax function instead load function , the result is the same.
Ext.Ajax.request({
url:'http://domain/path',
method:'post',
params:params,
});
I check the xhr within network of browser , it is a string as follows:
t1:[object Object]
t1:[object Object]
t2:ddd
when I check the server log, it shows :
t1:'[object Object]'
t1:'[object Object]'
t2:'ddd'
I found the solution , thank you
1, just use jsonData instead params during Ajax, like follows:
Ext.Ajax.request({
url: ajmd.util.version.getHost()+'/archimedes/update/selfInfo',
method:'post',
// params:params,
jsonData:params
});
2, or just encode the data before send
params.t1 = Ext.encode(params.t1);
If you name the parameter "foo[]", then it will encode it as a POST array making it easy to consume on the server side. Note the [] at the end.
var companies = [1,2,3];
Ext.Ajax.request({
url: '...',
method: "post",
params: {
'companies[]': companies,
},
success: function (response) {
console.log("done");
}
});

Setting Default Options for Backbone Collections

I have a Backbone Collection like so:
var ThreadCollection = Backbone.Collection.extend({
url: '/api/rest/thread/getList'
});
var myCollection = new ThreadCollection();
And then I'm fetching it from the server using the data object to append the query parameters (so in this case it comes out '/api/rest/thread/getList?userId=487343')
myCollection.fetch({
data: {
userId: 487343
}
})
There are other parameters that I may want to use instead of userId (groupId, orgId, etc) but I'd ideally define the data parameters upon initialization and from then on be able to run fetch() without specifying. Something like this:
var myCollection = new ThreadCollection({
data: {
userId: 487343
}
});
myCollection.fetch()
but it doesn't work. Does anyone know if there's a way to do this? Thanks!
One way is to define a custom fetch method on your collection which calls the super fetch method with some overridable defaults:
var ThreadCollection = Backbone.Collection.extend({
url: '/api/rest/thread/getList',
fetch: function(options) {
return Backbone.Collection.prototype.fetch.call(this, _.extend({
data: {
userId: 48743
}
}, options));
}
});
var myCollection = new ThreadCollection();
myCollection.fetch();

Wrapping my head around a unique backbone.js collection

I'm working out my first backbone.js app and have run into a bit of a wall. Perhaps someone can help me past this hurdle (gap in my understanding). What I want/need to do is to return the collection data to my router, so I can bind it to a Kendo UI Grid, but I'm not seeing any of the search results in my collection... I figure I must be missing something fundamental, but I'm not sure what it is.
Here is what I have so far:
ES.Router = Backbone.Router.extend({routes: {
'': 'search',
'search': 'search',
'results': 'results'
},
results: function() {
var resultsData = new ES.Results();
var boo = resultsData.fetch({
data: JSON.stringify({"query":"myquery"}),
type: 'POST',
contentType: 'application/json'
});
console.log(boo);
}});
ES.Result = Backbone.Model.extend();
ES.Results = Backbone.Collection.extend({
model: ES.Result,
url: '/search/query'
});
There are a few issues here:
A fetch should be a GET, not a POST, because a fetch should not save or modify anything
Maybe just a personal preference, but I'd url as a function, so as to avoid trying to modify the AJAX request options manually.
The fetch call will always be asynchronous, so you need to either add a success callback in the options hash, or add a listener to the collection's reset event
I'd write the collection like this:
ES.Results = Backbone.Collection.extend({
initialize: function() {
this.query = "test";
},
model: ES.Result,
url: function() {
return '/search/query?query=' + this.query;
}
});
Then set the search when you create the collection:
var resultsData = new ES.Results();
resultsData.query = "soccer";
And use success and/or the on("reset") event to handle the result:
resultsData.on("reset", function(collection) {
console.log(collection);
});
console.log("Fetching....");
resultsData.fetch({
success: function(collection, response) {
console.log("Got data!" + collection.length);
},
error: function(collection, response) {
console.log("Error: " + response.responseText);
}
});
​

How to specify url and header in backbone to use crud method on my model?

i need to make request on server that needs of particulary api key and i need to use the crud method tu update my model and as soon as...
For example i have this code in ajax to get element from server:
function getapi() {
$.ajax({
url: 'https://api.parse.com/1/classes/autolavaggi/QSfl*****',
type: 'GET',
dataType: 'json',
success: function(obj) {
alert("nome autolavaggio "+obj.nome);
},
error: function() {
alert('Errore');
},
beforeSend: setHeader
});
}
//GET GET GET GET GET GET GET GET Header Header Header Header
function setHeader(xhr) {
xhr.setRequestHeader('X-Parse-Application-Id', 'aqLJlmE2rRXBOy***************');
xhr.setRequestHeader('X-Parse-REST-API-Key', 'gvT2Isd5vAvjgq*****************');
}
How can i do to assign this particular ajax call to crud method save,fetch or another??
Each of the crud methods accept an options hash that will get forwarded to the ajax call. In the case of a collection fetch:
var Model = Backbone.Model.extend({});
var Collection = Backbone.Collection.extend({
model: Model,
url: 'https://api.parse.com/1/classes/autolavaggi/QSfl*****'
});
var setHeader = function (xhr) {
xhr.setRequestHeader('X-Parse-Application-Id', 'aqLJlmE2rRXBOy***************');
xhr.setRequestHeader('X-Parse-REST-API-Key', 'gvT2Isd5vAvjgq*****************');
}
var collection = new Collection();
collection.fetch({ beforeSend: setHeader });
Alternatively, override sync:
var sync = Backbone.sync;
Backbone.sync = function(method, model, options) {
options.beforeSend = function (xhr) {
xhr.setRequestHeader('X-Parse-Application-Id', 'aqLJlmE2rRXBOy***************');
xhr.setRequestHeader('X-Parse-REST-API-Key', 'gvT2Isd5vAvjgq*****************');
};
// Update other options here.
sync(method, model, options);
};

Resources