Basic routing with two properties - url-routing

I make this routing test with properties, search and registration for vehicles
my code
$(function() {
Router = can.Control({
"vehicles" : function(){
console.log("the hash is #!vehicles")
},
"vehicles/:registration" : function(data){
console.log("the hash is #!vehicles/:registration "+data)
},
"vehicles/:search" : function(data){
console.log("the hash is #!vehicles/:search "+data)
}
});
can.route("vehicles");
can.route("vehicles/:registration");
can.route("vehicles/:search");
can.route.ready();
new Router(document);
});
and the tests
Test one
can.route.attr("search", "121-TYU-898")
a {_data: Object, _cid: ".map1", _computedBindings: Object, __bindEvents: Object, _bindings: 2…}
__bindEvents: Object
_bindings: 2
_cid: ".map1"
_computedBindings: Object
_data: Object
route: "vehicles/:search"
search: "121-TYU-898"
__proto__: t.Construct
That ok, but no message ("the hash is #!vehicles/:search "+data) in console
Test two
can.route.attr("registration", "333-TYU-898")
a {_data: Object, _cid: ".map1", _computedBindings: Object, __bindEvents: Object, _bindings: 2…}
__bindEvents: Object
_bindings: 2
_cid: ".map1"
_computedBindings: Object
_data: Object
registration: "121-TYU-898"
route: "vehicles/:registration"
__proto__: t.Construct
That ok, but no message ("the hash is #!vehicles/:registration "+data) in console
Test three
can.route.attr("search", "444-TYU-555")
a {_data: Object, _cid: ".map1", _computedBindings: Object, __bindEvents: Object, _bindings: 2…}
__bindEvents: Object
_bindings: 2
_cid: ".map1"
_computedBindings: Object
_data: Object
registration: "121-TYU-898"
route: "vehicles/:registration"
search: "333-TYU-808"
__proto__: t.Construct
I don't understand, for me, i expect this answer
a {_data: Object, _cid: ".map1", _computedBindings: Object, __bindEvents: Object, _bindings: 2…}
__bindEvents: Object
_bindings: 2
_cid: ".map1"
_computedBindings: Object
_data: Object
route: "vehicles/:search"
search: "444-TYU-555"
__proto__: t.Construct
Could you help to understand, thank you
Thank a lot Daff and i can make this ?
listen when property page is a particular value ?
example
$(function() {
Router = can.Control({
"route": function(){
console.log("the hash is empty")
},
'{can.route} page=search': function(data){
console.log("the hash is "+data.page+" with id "+data.id )
},{can.route} page=registration': function(data){
console.log("the hash is "+data.page)
}
});
can.route(':page/:id');
can.route.ready();
new Router(window);
});
and
can.route.attr({page: "search", id: "123-jlkj-1231"})
and display in console
the hash is search with id 123-jlkj-1231
I tested, but this doesn't work :)
Do you see what I want to do ?

Imagine the CanJS route placeholders like variable names in JavaScript. Something like
function first(param1) {
}
and
function first(param2) {
}
Are the same as is vehicles/:registration and vehicles/:type matching the same route. What you probably want to do is this:
var Router = can.Control({
"vehicles route" : function(){
console.log("the hash is #!vehicles")
},
"vehicles/:type route" : function(data){
console.log(data.type);
}
});
new Router(document);
can.route.ready();
As shown in this Fiddle: http://jsfiddle.net/4M58j/
You can also match routes like "vehicles/search" and "vehicles/registration route" (notice the missing : which is used as a variable palceholder.

Related

Serialize Object into Form Data

I am trying to submit a request with form data like this:
playdate: 2017-08-06
players[1][name]: Alex
players[1][username]: Alex
players[1][score]: 51
However, if I add a players object like this:
var players = grid.getSelectionModel().getSelection().map(function(record) {
return record.getData();
});
form.submit({
url:'log.php'
params: {
players: players
}
});
then ExtJS submits it like this:
playdate: 2017-08-06
players: [object Object]
Doesn't ExtJS support serializing an object for a form-urlencoded request?
Relevant fiddle
Have a look at the documentation.
It should work using the property jsonSubmit:true in your submit-call:
form.submit({
url:'log.php'
params: {
players: players
},
jsonSubmit: true
});

How to get nested object's attributes from model.toJSON

I am learning Backbone.js. I have a model call myModel, and here is the console.log result when I call myModel.toJSON():
Object {accountId: "523f628e80d52a2805000004", added: "2013-09-26T06:26:12.765Z", updated: "2013-09-26T06:26:12.765Z", _id: "5243d384951b6cef05000004", name: Object}
I want to get the attributes in name, when I console.log myModel.toJSON().name, I got this result:
Object {first: "myfirst", last: "mylast"}
Everything works fine, until I call myModel.toJSON().name.first, I got a console error says
Cannot read property 'first' of undefined
I thought myModel.toJSON().name is an object, and to get the 'first' attribute from it, I just need to do myModel.toJSON().name.first. Any thought why it doesn't work?
This is the entire model I have:
r {cid: "c71", attributes: Object, collection: r, _changing: false, _previousAttributes: Object…}
_changing: false
_events: Object
_pending: false
_previousAttributes: Object
attributes: Object
_id: "5243d384951b6cef05000004"
accountId: "523f628e80d52a2805000004"
added: "2013-09-26T06:26:12.765Z"
name: Object
first: "myfirst"
last: "mylast"
__proto__: Object
updated: "2013-09-26T06:26:12.765Z"
__proto__: Object
changed: Object
cid: "c71"
collection: r
__proto__: s

Backbone+Parse.com Collection.fetch() returns empty array using event callback

i'm starting using parse.com to develop a web app but i'm stuck on a simple problem.
I defined a model (or object in Parse SDK) as:
Book.Model = Parse.Object.extend("book", {
// Default attributes for the book.
defaults: {
title: "placeholder...",
},
// Ensure that each book created has `title`.
initialize: function() {
if (!this.get("title")) {
this.set({"title": this.defaults.title});
}
},
});
and a collection:
Book.List = Parse.Collection.extend({
// Reference to this collection's model.
model: Book.Model,
initialize: function() {
},
});
Then, if i try something like
var books = new Book.List();
books.fetch({
success: function(collection) {
console.warn(collection);
},
error: function(collection, error) {
// The collection could not be retrieved.
}
});
Everything goes fine. Log:
child {length: 5, models: Array[5], _byId: Object, _byCid: Object, model: function…}
_byCid: Object
_byId: Object
length: 5
models: Array[5]
__proto__: EmptyConstructor
BUT if i try to use event callback instead of success method i get an empty array. Code:
books.on('reset', this.log());
books.fetch();
log: function() {
console.log(books);
}
and log:
child {length: 0, models: Array[0], _byId: Object, _byCid: Object, model: function…}
_byCid: Object
_byId: Object
length: 5
models: Array[5]
__proto__: EmptyConstructor
which is quite strange (because i think that each solution wait for the collection to be populated from the server). Does anybody know why is this happening?
I'm actually using Backbone Boilerplate and Parse.com js SDK.
The Collection#fetch behavior has changed, it used to reset the collection by default but as of 1.0.0 it merges the new models using set:
When the model data returns from the server, it uses set to (intelligently) merge the fetched models, unless you pass {reset: true}, [...]
and set doesn't trigger "reset" events, it triggers other events:
All of the appropriate "add", "remove", and "change" events are fired as this happens.
If you want your fetch to reset the collection then you have to say so:
books.fetch({ reset: true });

model's fetch does not work

Here is body of my model
urlRoot: '/users',
parse: function(response) {
return response.User;
}
Here is what is returned when I type /users/1 in my browser:
{"User":{"id":"1","created":"2013-02-13 09:22:42","modified":"2013-02-13 09:22:42","username":"somesuername","password":"","role":"somerole","token":null,"token_expiration":null}}
So the api works.
When I execute this:
this.model.id = 1;
this.model.fetch({ success: function(user){
console.log(user);
}}); // this.model is instance of my model
I get in console:
d {cid: "c4", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object…}
_changing: false
_pending: false
_previousAttributes: Object
attributes: Object
__proto__: Object
changed: Object
cid: "c4"
id: Array[1]
__proto__: e
So the result was successful by model didn't fetch any data - am I missing something?
Backbone.Model stores the data inside the attributes property. From Backbone documentation:
The attributes property is the internal hash containing the model's state — usually (but not necessarily) a form of the JSON object representing the model data on the server. It's often a straightforward serialization of a row from the database, but it could also be client-side computed state.
Please use set to update the attributes instead of modifying them directly.
Try expanding the attributes node in the console object inspector, and you should see your data.

get not retrieving name attribute from object

From the backbone docs
getmodel.get(attribute)
Get the current value of an attribute from the model. For example: note.get("title")
I seeded some data with a name for each country into a Rails app
Country.create!(name: "Brazil")
Country.create!(name: "France")
Country.create!(name: "Germany")
Country.create!(name: "Spain")
In the console, I created a new collection and fetched the data
countries.fetch();
Object
XHR finished loading: "http://localhost:3000/countries".
Checked the length. Equal to the four countries I created.
countries.length
4
Selected a random one using underscore's shuffle method.
c = countries.shuffle()[0]
The object has a name
Backbone.Model
_changes: Array[2]
_currentAttributes: Object
_events: Object
_hasComputed: false
_previousAttributes: Object
attributes: Object
country: Object
created_at: "2013-01-07T06:09:43Z"
id: 2
name: "France"
updated_at: "2013-01-07T06:09:43Z"
__proto__: Object
__proto__: Object
Tried to get the name attribute from the object several different ways, all without success
c.get('name')
undefined
c.get("name");
undefined
c.get("name")
undefined
Can anyone think what I might be doing wrong?
One thing that I find unusual is that there is a 'country' attribute wrapping the other attributes
attributes: Object
country: Object
created_at: "2013-01-07T06:09:43Z"
id: 2
name: "France"
updated_at: "2013-01-07T06:09:43Z"
I'm not sure why 'country' is wrapping the other data. Is it because I created the seed data with a Country model?
Country.create!(name: "Brazil")
anyways, obj.get('country') doesn't return undefined
c = countries.shuffle()[0]
k = c.get('country')
Object
created_at: "2013-01-07T06:09:43Z"
id: 3
name: "Germany"
updated_at: "2013-01-07T06:09:43Z"
__proto__: Object
but I can't do a get on the name after that (i.e after I did the get on country)
k = c.get('country')
Object
k.get('name')
undefined
Is there a way to remove the country wrapper and just be able to do get on the attributes that it was created with?
Override model.parse to extract the country element. Backbone calls parse before populating the model from fetched data:
var Country = Backbone.Model.extend({
parse: function(attributes) {
return attributes.country;
}
});

Resources