how to use spinejs fetch ajax data with conditions - javascript

For example, I have this Model as Users:
var Users = Spine.Model.sub();
Users.configure('Users', 'name', 'gender', 'age');
Users.extend(Spine.Model.Ajax);
Users.extend({url:"/users"});
Assume that we already have some data saved in database.
If run
var users = Users.fetch();
Ajax will send a GET request to /users, and all results will be returned.
But if I wanna fetch all female or male users, or age above 25, or top 10 users in specified order, how to pass these variables? I cant find spec in the document. The fetch method can pass a callback function parameter to revoke when fetch complete, clearly not what I want.

I found the solution myself..Actually the document tells how to paginate results.
var Photo = Spine.Model.sub();
Photo.configure('Photo', 'index');
Photo.extend(Spine.Model.Ajax);
Photo.extend({
fetch: function(params){
if ( !params && Photo.last() )
params = {data: {index: this.last().id}}
this.constructor.__super__.fetch.call(this, params);
}
});
But I found the code can't run, first
this.constructor.__super__.fetch.call(this, params);
should be
this.__super__.constructor.fetch.call(this, params);
secondly, if run Photo.fetch({data:{id:1}}), it will send a GET request like this
GET /photos?[object%20Object]
correct it
Photo.fetch({data: $.param({id:1})});
HTTP Request
GET /photos?id=1

Related

Ember data - One model, two endpoints

In ember data, if you want to fetch the collection of a model, it's convention to use this:
this.store.findAll('order');
or with a filter, this:
this.store.find('order', {shopId: 63});
So you pass the model name, and Ember-data will build the URL for you, which would look something like (depending on your adapter):
GET /api/orders
GET /api/orders?shopId=63
So this does two things
Build the URL to fetch data from the api
Map the collection as JavaScript objects, using the model that you passed as 1st argument
But what if I want to fetch orders from two URLs; /api/orders and /api/new_orders ?
The first one will work as usual: this.store.findAll('order'), but is there a way to override the api path that you fetch from?
Maybe something like this.store.find('order', {path: '/new_orders'})?
So that I can end up with a collection of objects modelled with my order model, but fetched from a different route
You need to have a rest adapter for this store and override the findAll method. The default implementation is as such
findAll: function(store, type, sinceToken) {
var query, url;
if (sinceToken) {
query = { since: sinceToken };
}
url = this.buildURL(type.modelName, null, null, 'findAll');
return this.ajax(url, 'GET', { data: query });
}
buildUrl will return a proper endpoint for your first url. you could then parse this url and modify it to make a second request with the same data, but with to your second endpoint. Than you could merge the responses or use them separately.
Reference: https://github.com/emberjs/data/blob/v1.13.5/packages/ember-data/lib/adapters/rest-adapter.js#L398

Backbone collection fetch imported incorrectly

I have a collection which is fetched from a REST endpoint, where it receives a JSON.
So to be completely clear:
var Products = Backbone.Collection.extend({
model: Product,
url : 'restendpoint',
customFilter: function(f){
var results = this.where(f);
return new TestCollection(results);
}
});
var products = new Products();
products.fetch();
If I log this, then I have the data. However, the length of the object (initial) is 0, but it has 6 models. I think this difference has something to do with what is wrong, without me knowing what is actually wrong.
Now, if I try to filter this:
products.customFilter({title: "MyTitle"});
That returns 0, even though I know there is one of that specific title.
Now the funky part. If I take the ENTIRE JSON and copy it, as in literally copy/paste it into the code like this:
var TestCollection = Backbone.Collection.extend({
customFilter: function(f){
var results = this.where(f);
return new TestCollection(results);
}
});
var testCollectionInstance = new TestCollection(COPY PASTED HUGE JSON DATA);
testCollectionInstance.customFilter({title: "MyTitle"});
Now that returns the 1 model which I was expecting. The difference when I log the two collections can be seen below. Is there some funky behaviour in the .fetch() I am unaware of?
Edit 2: It may also be of value that using the .fetch() I have no problems actually using the models in a view. It's only the filtering part which is funky.
Edit 3: Added the view. It may very well be that I just don't get the flow yet. Basically I had it all working when I only had to fetch() the data and send it to the view, however, the fetch was hardcoded into the render function, so this.fetch({success: send to template}); This may be wrong.
What I want to do is be able to filter the collection and send ANY collection to the render method and then render the template with that collection.
var ProductList = Backbone.View.extend({
el: '#page',
render: function(){
var that = this; /* save the reference to this for use in anonymous functions */
var template = _.template($('#product-list-template').html());
that.$el.html(template({ products: products.models }));
//before the fetch() call was here and then I rendered the template, however, I needed to get it out so I can update my collection and re-render with a new one (so it's not hard-coded to fetch so to speak)
},
events: {
'keyup #search' : 'search'
},
search : function (ev){
var letters = $("#search").val();
}
});
Edit: New image added to clearify the problem
It's a bit tricky, you need to understand how the console works.
Logging objects or arrays is not like logging primitive values like strings or numbers.
When you log an object to the console, you are logging the reference to that object in memory.
In the first log that object has no models but once the models are fetched the object gets updated (not what you have previously logged!) and now that same object has 6 models. It's the same object but the console prints the current value/properties.
To answer your question, IO is asynchronous. You need to wait for that objects to be fetched from the server. That's what events are for. fetch triggers a sync event. Model emits the sync when the fetch is completed.
So:
var Products = Backbone.Collection.extend({
model: Product,
url : 'restendpoint',
customFilter: function(f){
var results = this.where(f);
return new TestCollection(results);
}
});
var products = new Products();
products.fetch();
console.log(products.length); // 0
products.on('sync',function(){
console.log(products.length); // 6 or whatever
products.customFilter({title: 'MyTitle'});
})
It seems like a response to your ajax request hasn't been received yet by the time you run customFilter. You should be able to use the following to ensure that the request has finished.
var that = this;
this.fetch({
success: function () {
newCollection = that.customFilter({ title: 'foo' });
}
});

Send javascript array object to ashx

I have an array of objects in javascript and I like to send this object to the server in a post request to ashx handler
I'm sending the information with this script:
var filtersArray = [{id:1, val:"filter1"}, {id:2, val:"filter2"}];
var object = {filters: filtersArray, id: 123, name: "object"};
$.post('handler.ashx', jQuery.param(object), function () {
//do some stuff
});
I can see in the chrome console the network params
Form Data
filters[0][id]:1
filters[0][val]:filter1
filters[1][id]:2
filters[1][val]:filter2
id:123
name:object
And in the handler I want to retrieve the parameter filter as an array, list or something.
I tried to do this: context.Request("filters[]") but the response is Nothing to retrieve the value I have to context.Request("filters[0][id]")
But this is not useful because the size of the list could be different in each request and with this solution I should have to add a parameter with the size and iterate parameters with this number.
Another option will be transfor to a JSON object and later deserialize the object in the server. But I prefer to not do that.
There is any other way to do this?

Fetch Backbone Collection by Model IDs list

I have a REST API serving a few URLs:
/rest/messages
provides all messages. A message is a JSON/Backbone Model
{
title: 'foo',
body : 'bar'
}
To get a single message I have:
/rest/messages/:id
Is it possible to fetch a Backbone Collection using message IDs array? I don't want the whole message list, but just a few messages I specify by ID.
I could fetch Models one-by-one and fill up the Collection, but I'm wondering if Backbone has a cleaner way to do this.
Thanks
According to documentation, you can pass ajax options to the fetch call. So, you can pass ids as data attribute to the fetch call being done and based on it, return the respective models from the server.
For example (when doing fetch),
collection.fetch({
data : {
message_ids : [1, 3, 5] // array of the message ids you want to retrieve as models
}
})
This message_id array will be accessible as parameters (not sure of the name in your case) in the server code being executed at /rest/messages, from there you can return only specific models based on ids you receive as message_ids. The only thing you need is, client side must be aware of the ids of all the message models it needs.
You can use any data structure instead of array to send message_ids.
The url property of collection reference to the collection location on the server. When you use fetch, backbone uses that url.
The url property can be also a function that returns the url. So you can do something like that:
var ids = [1,2,3]
var messages = new MessegecCollection();
messages.url = function() {
return "/rest/messages/"+ids.join("-"); //results "/rest/messages/1-2-3"
}
messages.fetch();
You can also create a method in your collection that generated and set the url, or even fetchs a set of models.
Now all you have to do is to support this url: /rest/messages/1-2-3
Hope this helps!

backbone.js - getting extra data along with the request

I have a collection which holds some of the users. Some information that is needed is how many total there are, how many pages, etc. How do I pass these back to the client? Or do they have to come from a separate view in which case I will need more than one ajax call? I'd like to have the collection fetch() and also receive some of this "meta data". What's a good way for handling this?
Generally, you need to handle this in the collection class' parse method. Its responsibility is to take the response and return back an array of model attributes. However, you could do more than that if you wished if you didn't mind the parse method having this additional responsibility.
UserList = Backbone.Collection.extend({
model: User,
url: '/users',
parse: function(data) {
if (!data) {
this.registered_users = 0;
return [];
}
this.registered_users = data.registered_users;
var users = _(data.users).map(
function(user_data) {
var user = {};
user['name'] = user_data.name;
return user;
}
);
return users;
    }
});
So in the trivial example above, presume the server returns a response which contains a count of registered users and and an array of user attributes. You would both parse through and return the user attributes and you would pick off the registered user count and just set it as a variable on the model.
The parse method would get called as part of a fetch. So no need to modify the fetch, just use the built-in hook method that you have.
Purists would say that you are giving the parse method a secondary responsibility which might surprise some people (e.g. returning something and modifying model state). However, I think this is okay.
One way to do this is to override the Collection::fetch() method so that it parses this metadata out of the response. You could have your backend return a response like this:
{
"collection": [
{ ... model 1 ... },
{ ... model 2 ... },
...
],
"total_rows": 98765,
"pages": 43
}
In your fetch method which overrides the original Backbone.Collection::fetch() method, you can handle each property of the object separately. Here's you could do the override with a slightly modified fetch method:
_.extend(Backbone.Collection.prototype, {
fetch : function(options) {
options || (options = {});
var collection = this;
var success = options.success;
options.success = function(resp) {
// Capture metadata
if (resp.total_rows) collection.total_rows = resp.total_rows;
if (resp.pages) collection.pages = resp.pages;
// Capture actual model data
collection[options.add ? 'add' : 'refresh'](
collection.parse(resp.collection), options);
// Call success callback if necessary
if (success) success(collection, resp);
};
options.error = wrapError(options.error, collection, options);
(this.sync || Backbone.sync).call(this, 'read', this, options);
return this;
});
Note that this approach using _.extend will affect all your classes which extend Backbone.Collection.
This way, you don't have to make 2 separate calls to the backend.
I would bootstrap the information at pagecreation. Write the information into the html document when the server creates the site. Like that you don't have to have an ajax call at all. I do that with the whole collection in ordner not to first load the page and then wait for the ajax call to return the information needed.
Code example with Python:
Line 64: https://github.com/ichbinadrian/maps/blob/master/python/main.py <- from here
Line 43: https://github.com/ichbinadrian/maps/blob/master/templates/index.html <- into here

Categories

Resources