Add values to a view with JSON and Backbone.js - javascript

I have a View (created using Backbone.View.extend) and a JSON object, I actually get the object from a couchdb database. How do I give the values to the view?
For example, I have these two objects:
var personJSON = {"name":"Buddy","email":"trout#fish.net"}
var personDetailsView; //Backbone.View
Is there a way to pass the values into the view without explicitly mapping them to the model?
I've found examples where you can add objects to a Backbone collections but not a view.

If you need to have access to the JSON object within the PersonDetailsView (Backbone.View) object, one way of doing this is to pass the JSON parameter as an option in the View's constructor:
//view definition
var PersonDetailsView = Backbone.View.extend({
initialize: function(){
this.person = this.options.person; //do something with the parameter
}
});
var personJSON = {"name":"Buddy","email":"trout#fish.net"};
var personDetailsView = new PersonDetailsView({ person : personJSON });
From Backbone's official documentation:
When creating a new View, the options you pass are attached to the view as this.options, for future reference.

Usually, you retrieve model via model collection and pass it to view:
var person=personCollection.find(1);
var view=new PersonView({model: person});
var personView = Backbone.View.extend({
template: JST['personTemplate'],
render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
$('#container').html(personView.render().el);

Related

How can we create an instance of Backbone view using the string name store in a javascript object?

I'm creating a visual builder using different view for each component. All the view are declared like below:
$(function() {
var parallaxView = new Backbone.view.extend({
....
});
var parallaxView = new Backbone.view.extend({
....
});
});
At one point i start to create a new object view from that view. But all i know is the string represent the name of the view store in an object
name
My question can we create an object in some way such as new class using that object value as class name.
var myView = new name(param1, param2);
instead of using
switch (name) {
case 1:
....
}
I have try this case
var myView = new name(param1, param2);
and i know that it won't wok. But is there any way to can create an object in someway like that?
If I understand your question in a right way, you can store views constructors in object like this:
$(function() {
window.views = {
'parallax': Backbone.View.extend({ /*...*/ }),
'test': Backbone.View.extend({ /*...*/ })
};
});
Then you can create instances this way:
// var name = 'parallax';
var myView = new window.views[name](param1, param2);
Please let me know if your problem is not like I understand it.

Accessing model ID in backbone.js

I’m building my first Backbone application, and I’m a little confused with how I pass an ID into a model. When I instantiate the model, I pass in the ID like this var user = new UserModel(id);. At that point, id == 1. The value is still the same in the initialize
method in the model. When I use that variable in the url property, it’s undefined. Why is that?
// Filename: models/user/UserModel.js
define([
'underscore',
'backbone'
], function(_, Backbone) {
var UserModel = Backbone.Model.extend({
initialize: function(id) {
console.log('modelID: ' + id); // Prints 'modelID: 1'
this.set({'id': id});
},
// Sends GET request to http://[domain]/users/view/undefined
url: 'users/view/' + this.id
});
return UserModel;
});
This one works:
var UserModel = Backbone.Model.extend({
initialize: function(id) {
console.log('modelID: ' + id); // Prints 'modelID: 1'
this.set({'id': id});
},
// Sends GET request to http://[domain]/users/view/undefined
url: function(){
return "/users/view/"+this.get("id");
}
});
console.log(new UserModel("10").url())
http://jsfiddle.net/wyA9Q/2/
A Backbone model expects an object representing the attributes as first argument to its constructor
constructor / initialize new Model([attributes], [options])
When creating an instance of a model, you can pass in the initial values of the attributes, which will be set on the model. If you define an initialize function, it will be invoked when the model is created.
Setting model.urlRoot will help build your URLs
urlRoot model.urlRoot or model.urlRoot()
Specify a urlRoot if you're
using a model outside of a collection, to enable the default url
function to generate URLs based on the model id. "[urlRoot]/id"
Attributes should be accessed via model.get
So you could define your model as
var UserModel = Backbone.Model.extend({
urlRoot: '/users/view'
});
and instantiate it as var user = new UserModel({id: id});
var userModel = new UserModel({id: 10});
userModel.fetch();
It should work :)

Access an objects content when creating a view from an internal function in ember.js

I have an ember.js Object that overrides the create method so I can pass some json of unknown structure to the objects content variable.
//model
App.Order = Ember.Object.extend({
content: null,
create: function(data) {
this.set('content', data);
return this._super();
},
getView: function() {
var self = this;
return Ember.View.create({
templateName: 'order-dialogue',
classNames: ['card'],
content: self.get('content'),
name: 'house'
});
}
});
I have a function that generates a view for the object however I am unable to access the parent objects content. Everytime I try, self.get('content') returns null.
Quesion:
How can the view generated in the getView function access the parent objects content?
I have an ember.js Object that overrides the create method so I can pass some json of unknown structure to the objects content variable.
Actually your object is not overriding the create method. It is defining a create function on the instance. So with the code you posted,
var order = App.Order.create({test: true});
console.log(order.get('content')); // undefined
To override the create method you need to reopenClass like this:
App.Order.reopenClass({
create: function(data) {
order = this._super();
order.set('content', data);
return order;
}
});
With that in place:
var order = App.Order.create({test: true});
console.log(order.get('content')); // {"test": true}
How can the view generated in the getView function access the parent objects content?
Exactly the way you coded it. There is nothing wrong with the view, it actually is returning the parent object's content. It's just that the parent object's content is not what you are expecting.
See this jsbin for a working example

How to call model's method from collection in backbone.js?

I've been trying to learn backbone.js these days. What I've is a model and a collection. The model has some default properties defined in it which I want to fetch within a collection. This is my code:
var model = Backbone.Model.extend({
defaults : {
done : true
}
});
var collection = Backbone.Collection.extend({
model : model,
pickMe : function () {
log(this.model.get('done')); //return undefined
}
});
var col = new collection();
col.pickMe();
How do I call methods defined in my model from collection? Am I doing wrong here?
The basic setup of Backbone is this :
You have models which are part of collection(s). So here in your setup you have a model constructor model and collection constructor collection, but you have no models in your collection and if you have any models they will be an array, so your code should be something like this
var model = Backbone.Model.extend({
defaults : {
done : true
}
});
var collection = Backbone.Collection.extend({
model : model,
pickMe : function () {
for ( i = 0; i < this.models.length; i++ ) {
log(this.models[i].get('done')); // this prints 'true'
}
}
});
// Here we are actually creating a new model for the collection
var col = new collection([{ name : 'jack' }]);
col.pickMe();
You can check the working jsFiddle here : http://jsfiddle.net/S8tHk/1/
#erturne is correct, you're trying to call a method on your model constructor, not a model instance. That doesn't make sense.
If you really want to define methods on the collection, then #drinchev provides an example of how to iterate through the models in the collection and invoke their methods. Although, the example is rather clunky -- using the built-in iterator methods would be more elegant.
Depending what you're trying to accomplish, you may want to just use the built-in collection iterator methods to invoke methods on each model instead of defining methods on the collection. E.g.:
var Model = Backbone.Model.extend({
defaults : {
done : true
}
});
var Collection = Backbone.Collection.extend({
model : Model
});
var col = new Collection([{}, {done : false}, {}]);
col.each(function (model) {
log(model.get('done'));
});
I think you'd better attach your model methods to the model itself, not in the collection. So you should have somethings like this:
var model = Backbone.Model.extend({
defaults : {
done : true
},
pickMe : function () {
log(this.get('done'));
}
});
var collection = Backbone.Collection.extend({
model : model,
});
var model = collection.get(id)
model.pickMe()

Is backbone.js model's view instance render function static?

This is a general question about backbone.js and javascript, I'm intermediate in javascript:
If you have a collection of models, each connected to an instance of a view, is each model instance's view instance containing a full instance of the view's render method? If so, what is recommended way to ensure that the render method is 'static', so that memory is not wasted if each model instance requires the exact same render function?
In the example below, does each hat instance also contain an instance of the render function, or is it pointing to a 'static' render function?
var Hat = Backbone.Model.extend({});
var HatCollection = Backbone.Collection.extend({
model : Hat,
});
var HatView = Backbone.View.extend({
render : function() {
// output the hat's html
}
});
var hats = new HatCollection([ new Hat(), new Hat(), new Hat()])
hats.each(function(hat) {
hat.view = new HatView({ model : hat });
});
There are no real "static" or "class" methods in Javascript. What you have is a method defined on the class's prototype.
When you use Backbone.View.extend(), everything you pass is added to the prototype, so they are indeed what you would call "static" methods.
Just check if the render method is a member of the instance or the prototype:
(function () {
var HatView = Backbone.View.extend({
render : function() {
console.log("rendering a hat...");
}
});
var hview = new HatView();
console.log(hview.hasOwnProperty("render")); // false
console.log(hview.render === HatView.prototype.render); // true
}());

Categories

Resources