Backbone Collection URL is Undefined - backbone.js

trying to pass the url to the fetchFromURL function but URL is undefined when loggin it. NO IDEA why this is happening!!
class Device extends Backbone.Model
class Devices extends Backbone.Collection
model: Device
localStorage: new Backbone.LocalStorage 'devices'
url: "http://192.168.2.17:8030/profile/RestProfile.svc/GetDeviceList/"
fetchFromURL: =>
collection = #
console.log #url
getView = =>
devices = new Devices
devices.fetch()
devices.fetchFromURL()

Related

Backbone.js How to retrieve a model in a nested collection?

I have a PizzaType model that has a nested collection of Pizzas. The Pizzas Collection is listed based on the Pizza Type. I would like to be able to click on a pizza in the pizzas collection and display its attributes.
What would be the best way to set the url params dynamically?
The url does not need a route to navigate to for bookmarking and sharing, just to retrieve the specific resource.
I have it so that if someone wants to view the pizza type the url is pizza_type/:id
:id is the id belonging to the Pizza Type (parent model)
I currently have it so if a pizza is clicked on in the Pizzas Collection (that belongs to the Pizza Type Model), the path to the pizza resource is not followed; just a region on the page is updated. The url path is needed so jQuery can get the resource to update that region. The url to the pizza is pizza_types/:pizza_type_id/pizzas/:id Here, the :id is the id belonging to the Pizza Model, and the :pizza_type_id is the foreign key that members of the Pizzas Collection share to group them into the collection, that belong to the Pizzas Type Model.
When I click on the pizza (id = 3), I get "NetworkError: 404 Not Found - http://localhost:3000/pizza_types/3/pizzas"
Here is the Model and Collection Code:
#Pizzeria.module "Entities", (Entities, App, Backbone, Marionette, $, _) ->
class Entities.PizzaType extends Backbone.Model
urlRoot: "pizza_types/"
# creates the nested collection
initialize: ->
#pizzas = new Entities.PizzasCollection
#pizzas.url = #urlRoot + #id + '/pizzas'
#pizzas.fetch
reset: true
parse: (response) ->
response
class Entities.PizzaTypesCollection extends Backbone.Collection
model: Entities.PizzaType
url: 'pizza_types'
parse: (response) ->
response
# Is there a way to pass in a :pizza_type_id and :id params to pass to the url() so
# that the specific pizza model can be retrieved from the collection?
class Entities.Pizza extends Backbone.Model
url: -> "pizza_types/" + 2 + "/pizzas/" + 4 # <-- Hard coded works, but how to set the params dynamically?
parse: (data) ->
data
class Entities.PizzasCollection extends Backbone.Collection
model: Entities.Pizza
url: 'pizzas'
parse: (data) ->
data
Any suggestions? Is this the proper way, I tried to do this as well:
class Entities.Pizza extends Backbone.Model
urlRoot: -> "pizza_types"
# I thought I could pass these params in and fetch the correct pizza model, but not working.
fetch
pizza_type_id: pizza_type_id
id: id
reset: true
parse: (data) ->
data
PizzaType Attributes with example data:
PizzaType: {
id: 2,
name: "Gourmet",
pizzas: [
0: {
id: 4,
pizza_type_id: 2
name: "gourmet pizza 1"
},
1: {
id: 5,
pizza_type_id: 2,
name: "gourmet pizza 2"
}
]
For url in pizza model you can specify an attribute like pizza_type for model in initialize function and change url function like this
class Entities.Pizza extends Backbone.Model
initialize: (options)->
#pizza_type = options.pizza_type if options.pizza_type
url: ->
"pizza_types/" + #pizza_type + "/pizzas/" + #id
parse: (data) ->
data
class Entities.PizzaType extends Backbone.Model
urlRoot: "pizza_types/"
url: ->
#urlRoot+#id+'/pizzas' if #id
initialize: ->
#pizzas = new Entities.PizzasCollection
#pizzas.fetch reset: true
parse: (response) -> response
In PizzasCollection add addOptions so when adding models to collection then backbone add with this default options
class Entities.PizzasCollection extends Backbone.Collection
model: Entities.Pizza
addOptions:
'pizza_type': #id
url: 'pizzas'
parse: (data) -> data
"NetworkError: 404 Not Found -
http://localhost:3000/pizza_types/3/pizzas"
This is a problem with your server, maybe mistyping, or trailing-slash problems or any server problems.
P.S : I recommend using a relational model (with any plugin can do that like BackboneRelationals)

Possible to have sub Collections in Collection?

I am learning Backbone.js and try to develop revamp a project using Backbong.js. As the project was already have APIs and was using in different platforms, iphone app, andorid app and web.
My problem is, there is a API return as below
{
success: true,
response: {
posts: [{...post data...}, {...post data...}, {...post data...}],
users: [{...user data...}, {...user data...}],
categories: [{...category data...}, {...category data...}]
}
}
as the backbone documentation
a Collection can contain many models
Typically the design is
// Post Model
var PostModel = Backbone.Model.extend({
...
})
// User Model
var UserModel = Backbone.Model.extend({
...
})
// Category Model
var UserModel = Backbone.Model.extend({
...
})
var PostListCollection = Backbone.Collection.extend({
model: PostModel
})
So... How can I put these 3 types of "objects" in the a Collection? Thanks
Unsure why you'd want a collection that isn't a single collection. It sounds like (and do correct me if this is wrong), you want a neat way of fetching your data from the API and turning it in to your three collections.
You could create a model that fetches from your API, that implements a custom parse function to create three collections within it.
Granted, you'll want to define UserCollection, PostCollection and CategoryCollection beforehand.
ApplicationModel = Backbone.Model.extend({
url: '/apiUrl/',
parse: function(data)
{
var result = {};
result.users = new UserCollection(data.users);
result.posts= new PostCollection(data.posts);
result.categories = new CategoryCollection(data.categories);
return result;
}
});
you can have a model that contain the collections
var ResultModel = Backbone.Model.extend({
default: {
Users: [],
Posts: [],
Categories: []
}
});
Then implements the collection in usual way.
So, when you try to get the child collections ...
var result = new ResultModel("your result JSON object");
var users = new UserCollection(result.get("Users"));
var posts = new PostCollection(result.get("Posts"));
var categories = new CategoryCollection(result.get("Category"));
This is working well for me ... in my case

BackboneJS MarionetteJS - waiting until collection has finished fetching

I have a BackboneJS & MarionetteJS app
class MyApp extends Marionette.Application
app = new MyApp
app.addRegions
tag_container :"#tag_container"
item_container :"#item_container"
app.addInitializer( =>
app.items = new ItemCollection()
app.item_container.show(new ItemListView({collection:app.items}))
)
In my ItemCollection,
class ItemCollection extends Backbone.Collection
model :ItemModel
url :"/get_items"
initialize: =>
#search()
search: =>
#reset()
#fetch()
Above code displays the ItemListView immediately and adds the items as they are being fetched.
How can I wait until the collection has finished fetching THEN display the ItemListView in the "item_container"?
Either use a listener to know when the collection has finished his job. You can listen to reset if you're resetting it (not the default behavior as of Backbone 0.9.10) or sync (always done).
Or you can use the success callback.
Source
A third solution would be to do a synchronous fetch:
#fetch async: false
fetch returns a jquery promise. so you can just do
collection.fetch().done(function() {
// create & show the view
});

Backbone.js set URL parameters in model & use it with fetch

I would like to fetch model from specific url with parameter:
url: server/somecontroller/id/?type=gift
Simple working way is:
collection.fetch({ data: { type: 'gift'} });
But I want to set it in model:
...
if(id){
App.coupon = new AffiliatesApp.Coupon({id: id});
} else {
App.coupon = new AffiliatesApp.Coupon({id: 'somecontroller'}, {type: 'gift'});
}
App.coupon.fetch();
How can I achieve it?
The easiest way to achieve this is to override Backbone's url method on the Coupon model with one defined by you. For example you can do :
Affiliates.Coupon = Backbone.Model.extend({
urlRoot : "server/somecontroller/",
url : function(){
var url = this.urlRoot + this.id;
if(this.get("type")){
url = url + "/?type=" + this.get("type");
}
return url;
}
});
This solution is easy to implement but has a drawback: the generated URL will be used for every action that syncs to the server (fetch,save,..).
If you need to have a finer control over the generation of the URL depending on what action you are doing you will need to override Backbone's Sync method for your model.
It can be done by overriding the fetch method in model to use some custom data. Using CoffeeScript it could look like this:
class AffiliatesApp.Coupon extends Backbone.Model
fetch: ->
super(data: { type: #get('type') })
Note that this example will ignore any attributes passed to coupon.fetch(), however it can be easily adjusted for any override logic.

Cakephp getting session variable in model without using Auth component

I want to get my session variables in my model. Im not using Auth component. Is there any alternate way ?
Thanks
Binoy
You would need to use the Session helper to do,
$this->Session->write('key','value');
But as the comment states, you'll be wanting to set a variable in your model and then use the session to write the same value into that variable in the model, rather than accessing the session actually in the model.
Class MyModel Extends AppModel{
var $username;
var $password;
}
Then in your controller you could use something along the lines of,
$this->MyModel->username = $this->Session->read('User.id');
$this->MyModel->password = $this->Session->read('User.password');
Controller File : use Session helper
class AppController extends Controller {
var $helpers = array('Session');
function index()
{
$this->Session->write('answer', '10'); //$this->Session->write('key','value');
}
....
}
Now you can access this varibale in your model :
class AppModel extends Model {
function validateanswer(){
CakeSession::read('answer');/*Here u can get value of varibale answer which you set through controller*/
}
}

Resources