backbone.js parse 1 element (the Id) - javascript

For a id on a model in backbone, its just id and all lower cased. What if my Id on the server is called UserId. In the parse method for backbone, how do I change UserId to id and use the same names for all other properties?
For eg.
window.User = Backbone.Model.extend({
defaults:
{
UserId: 0, // <--can i just tell backbone that this is my id?
Name: '',
Age: 0
}
parse: function(response){
var model = response;
model.id = response.UserId;
return model;
}
});
Is there a better way to do this?
How about telling backbone model that my id is of type UserId.

You have to say Backbone what property is your id using the idAttribute in the model:
window.User = Backbone.Model.extend({
idAttribute: "UserId",
...
})
and everything works fine :). Backbone will create a id property for you and collections of this model will get() by your UserId.

Do it like so:
parse: function(response) {
var attrs = {};
attrs.id = response.UserId;
return attrs;
}
Parse has the responsibility to return an attributes hash, not a model. As such, you need only transform the response into an attributes hash versus a model as you are doing.

To set the id i would do as mauromartini says. To change any other property you don't need to create any private variables, response from the server is just an object so manipulate it and return it.
window.User = Backbone.Model.extend({
defaults: { UserId: 0 },
parse: function(response){
response.id = response.UserId;
return response;
}
});
you could also add the following before you return the object if you want to keep the model clean:
delete response.UserId;

Related

How can I fake Collection data?

What I mean by this is I want to create it artificially.
This is for testing purposes.
But for models, it is quite simple. I just set defaults I instantiate the model object and from there I can use this.model.toJSON() to grab the created data.
I want to use this same trick with collections. Is there a similar way to do this with collections? What I would want to do is have the collection create x ( 8 in this case ) copies of Model defaults.
Basically what I was doing before for models but a little bit more complex as it applies to Collections.
Here is the actual use case. It should be simple.
/**Model
**/
// name, picture, time, tweet, h_file
var FeedRow = Backbone.Model.extend({
Name: 'FeedRow',
defaults: {
name: "default",
picture: 0,
time: "0",
tweet: "default",
h_file: "default"
}
});
/**Collection
**/
var FeedTable = Backbone.Collection.extend({
Name: 'FeedTable',
model: FeedRow
});
When your FeedTable collection is constructed you could set the model on it multiple times in the initialize method.
var FeedTable = Backbone.Collection.extend(
{
Name: 'FeedTable',
model: FeedRow,
initialize: function()
{
model = this.model;
models = [];
_.times(8, function(n)
{
models.push(new model({id: (n + 1)}));
});
this.set(models);
}
});

In an EmberJS model, is there a better way to parse and bind to a json object as an attribute?

This is for parsing and binding a json object as an attribute (there's a transform as well, but it's very basic):
cleanCredentials: ->
creds = #get('credentials')
Object.keys(creds).forEach (key) =>
unless key in #get('selectedDriver').api_keys
delete #get('credentials')["#{key}"]
get_set: ->
key = arguments[0][0]
value = arguments[0][1]
if (arguments[0].length > 1)
#set "credentials.#{key}", value
#cleanCredentials()
#get "credentials.#{key}"
getter_setter = `function(key, value) { return this.get_set(arguments); }.property('credentials')`
apiToken: getter_setter
applicationId: getter_setter
applicationUserId: getter_setter
companyCode: getter_setter
username: getter_setter
It works, and I understand it, but is there a better way?
IIUC, you should define custom transform:
App.RawTransform = DS.Transform.extend({
deserialize: function(json) {
return json;
},
serialize: function(object) {
return object;
}
});
App.Model = DS.Model.extend({
rawJSONobject: DS.attr('raw')
});
This solution won't be able to bind to individual items within the json string but will watch the entire json string... Also, haven't been able to test this, but hopefully this will give you some ideas.
App.Person = Ember.Model.extend({
// json string
'jsonData' : DS.attr('string'),
// computed property
'parsedData' : function(key, value) {
// setter -- take an object and save the stringified version to the model
if (arguments.length > 1) {
this.set('jsonData', JSON.stringify(value));
}
// return the parsed json string rather than the string itself...
return $.parseJSON(this.get('jsonData'));
}.property('jsonData')
});

Converting JSON data to Backbone Model with child Collection

I am working with a Playlist object which has some properties defining itself as well as a PlaylistItem collection.
When I receive data from my server, I get its JSON response in my client-side success method:
success: function (data) {
console.log("JSON data:", data);
playlists = _.map(data, function (playlistConfig) {
return new Playlist(playlistConfig);
});
...
}
Here, I convert my JSON data into Playlist objects. Each Playlist object is a Backbone.Model.
Here's how my data looks:
And here's what the Playlist constructor looks like:
return function(config) {
var playlist = new Playlist(config);
return playlist;
};
var Playlist = Backbone.Model.extend({
defaults: function() {
return {
id: null,
userId: null,
title: 'New Playlist',
selected: false,
position: 0,
shuffledItems: [],
history: [],
items: Backbone.Collection.extend({
model: PlaylistItem
})
};
},
...
}
My problem:
If I create a Playlist object with defaults, it initializes with an empty Backbone.Collection for PlaylistItem. However, if I create a Playlist object with an already-defined collection, I get a basic array and not a Backbone.Collection. This is because I am working with JSON data from the server which has not been converted to Backbone entities yet. That data is extended over the Playlist's defaults and overwrites the Backbone.Collection entity.
What is a proper way to initialize with a populated Backbone.Collection? I could write code in Initializes which checks the type of my items array and if it is not a Backbone.Collection I could create a new Backbone.Collection and add the items to it and then replace the old array with the new one, but that seems really hoakey.
Don't define your PlalistItems Collection inside defaults, but beforehand.
Then, create an initialize method on your Playlist Model like so:
var PlaylistItems = Backbone.Collection.extend({
...
});
var Playlist = Backbone.Model.extend({
initialize: function() {
this.set('items', new PlaylistItems(this.items));
},
defaults: function() {
return {
id: null,
userId: null,
title: 'New Playlist',
selected: false,
position: 0,
shuffledItems: [],
history: [],
items: [] // don't define your PlaylistItems Collection here
};
}
});
Check out the fiddle here: http://jsfiddle.net/georgedyer/r2XKb/
(you'll need to open the console to see the collection)
Another issue I ran into was after you save your model to the server you will get back a response that will change your embedded collection into a regular javascript array. To remedy this I had to override the parse function on my model class like so:
var model = backbone.Model.extend({
urlRoot : "/rest/model",
initialize: function(){
this.set("myCollection", new MyCollection(this.myArray));
},
defaults: {
myArray: []
},
parse: function(response){
this.set(response);
this.set("myArray", new MyCollection(response.myArray));
}
});

MongoError: cannot change _id of a document

I'm newbie to MongoDB and Backbone, so I try to understand them, but it is hard. I have a big, big problem: I cannot understand how to manipulate attributes in Backbone.Model to use in Views only what I need. More specific - I have a model:
window.User = Backbone.Model.extend({
urlRoot:"/user",
idAttribute: "_id",
defaults: {
_id: null,
name: "",
email: "foo#bar.baz"
}
});
window.UserCollection = Backbone.Collection.extend({
model: User,
url: "user/:id"
});
And I have a View:
beforeSave: function(){
var self = this;
var check = this.model.validateAll();
if (check.isValid === false) {
utils.displayValidationErrors(check.messages);
return false;
}
this.saveUser();
return false;
},
saveUser: function(){
var self = this;
console.log('before save');
this.model.save(null, {
success: function(model){
self.render();
app.navigate('user/' + model.id, false);
utils.showAlert('Success!', 'User saved successfully', 'alert-success');
},
error: function(){
utils.showAlert('Error', 'An error occurred while trying to save this item', 'alert-error');
}
});
}
I have to use 'put' method whit data from any fields except '_id', so it must be smth like:
{"name": "Foo", "email": "foo#bar.baz"}
But every time, doesn't depend on what I do it send
{**"_id": "5083e4a7f4c0c4e270000001"**, "name": "Foo", "email": "foo#bar.baz"}
and this error from server:
MongoError: cannot change _id of a document old:{ _id: ObjectId('5083e4a7f4c0c4e270000001'), name: "Foo" } new:{ _id:
"5083e4a7f4c0c4e270000001", name: "Bar", email: "foo#bar.baz" }
Github link: https://github.com/pruntoff/habo
Thanks in advance!
From looking at your mongo error, the problem is not with mongo, it is just doing what it's supposed to do. It had an object with _id of ObjectId type: ObjectId('xxx') and now you're trying to change that object to have an _id of a String type (_id: "5083e4a7f4c0c4e270000001") and that Mongo apparently does not like.
So, the question is: why did the object have an id of type ObjectId in the first place? How did you set it the first time? If you used some other method to initialize it (I'm guessing server side), you should set the id type to be a String so that it is the same as the one coming from your script library. If you want it to stay an ObjectId, you will need to convert the String coming from your script to an ObjectId before you save it to Mongo.
HTH.
MongoDB creates _id as an ObjectID, but doesn't retrieve _id as an ObjectID.
Whether this inconsistency is 'correct behaviour' or not, it is certainly an annoying surprise for most MongoDB users.
You can fix it with:
if ( this._id && ( typeof(this._id) === 'string' ) ) {
log('Fixing id')
this._id = mongodb.ObjectID.createFromHexString(this._id)
}
See MongoDB can't update document because _id is string, not ObjectId

Backbone.js model with collection

I have 2 models and one collection. JobSummary is a model, JobSummaryList is a collection of JobSummary items, and then I have a JobSummarySnapshot model that contains a JobSummaryList:
JobSummary = Backbone.Model.extend({});
JobSummaryList = Backbone.Collection.extend({
model: JobSummary
});
JobSummarySnapshot = Backbone.Model.extend({
url: '/JobSummaryList',
defaults: {
pageNumber: 1,
summaryList: new JobSummaryList()
}
});
When I call fetch on the JobSummarySnapshot object, it gets everything... Except when I move through the summaryList collection they are all of type object and not JobSummary.
I suppose this makes sense since other than the defaults object, it doesn't know that the summaryList should be of type JobSummaryList. I can go through each item and convert it to a JobSummary object, but I was hoping there was a way to do it without having to do it manually.
Here's my test code (working jsfiddle here):
var returnData = {
pageNumber: 3,
summaryList: [
{
id: 5,
name: 'name1'},
{
id: 6,
name: 'name2'}
]
};
var fakeserver = sinon.fakeServer.create();
fakeserver.respondWith('GET', '/JobSummaryList', [200,
{
'Content-Type': 'application/json'},
JSON.stringify(returnData)]);
var callback = sinon.spy();
var summarySnapshot = new JobSummarySnapshot();
summarySnapshot.bind('change', callback);
summarySnapshot.fetch();
fakeserver.respond();
var theReturnedList = callback.getCall(0).args[0].attributes.summaryList;
_.each(theReturnedList, function(item) {
console.log('Original Item: ');
console.log(item instanceof JobSummary); // IS FALSE
var convertedItem = new JobSummary(item);
console.log('converted item: ');
console.log(convertedItem instanceof JobSummary); // IS TRUE
});
UPDATE:
It occurred to me that I could override the parse function and set it that way... I have this now:
JobSummarySnapshot = Backbone.Model.extend({
url: '/JobSummaryList',
defaults: {
pageNumber: 1,
summaryList: new JobSummaryList()
},
parse: function(response) {
this.set({pageNumber: response.pageNumber});
var summaryList = new JobSummaryList();
summaryList.add(response.summaryList);
this.set({summaryList: summaryList});
}
});
This works so far. Leaving the question open in case someone has comment on it....
Your parse() function shouldn't set() anything, its a better practice to just return the attributes, Backbone will take care of setting it. e.g.
parse: function(response) {
response.summaryList = new JobSummaryList(response.summaryList);
return response;
}
Whatever you return from parse() is passed to set().
Not returning anything (which is like returning undefined) is the same as calling set(undefined), which could cause it not to pass validation, or some other unexpected results if your custom validate()/set() methods expects to get an object. If your validation or set() method fails because of that, the options.success callback passed to Backbone.Model#fetch() won't be called.
Also, to make this more generic, so that set()ing to a plain object from other places (and not only from the server response) also effects it, you might want to override set() instead:
set: function(attributes, options) {
if (attributes.summaryList !== undefined && !(attributes.summaryList instanceof JobSummaryList)) {
attributes.summaryList = new JobSummaryList(attributes.summaryList);
}
return Backbone.Model.prototype.set.call(this, attributes, options);
}
You might also find Backbone-relational interesting - it makes it much easier to deal with collections/models nested inside models.
edit I forgot to return from the set() method, the code is now updated

Categories

Resources