Backbone js passing arguments - javascript

I'm new at reading Backbone js and I have some serious problems with passing arguments in Backbone js.
var Song = Backbone.Model.extend();
var Songs = Backbone.Collection.extend({
model: Song
});
var SongView = Backbone.View.extend({
el: "li",
render: function() {
this.$el.html(this.model.get("title"));
return this;
}
});
var SongsView = Backbone.View.extend({
el: "ul",
initialize: function() {
this.model.on("add", this.onSongAdded, this);
},
onSongAdded: function(song) { // when object is added to a collection add event is triggerd
// the handler for this event get an argument which is the object that was just added
//in this case it refers to a song model so we simply pass it to our songView which is responsible for rendering a song an then we use jquery append method
// to append it to our list
var songView = new SongView({
model: Song
});
this.$el.append(songView.render().$el);
},
render: function() {
var self = this;
this.model.each(function(song) { //
var songView = new SongView({
model: Song
});
self.$el.append(songView.render().$el);
});
}
});
var songs = new Songs([
new Song({
title: "1"
}),
new Song({
title: "2"
}),
new Song({
title: "3"
})
]);
var song_1 = new Song({
title: "hello"
});
var songsView = new SongsView({
el: "#songs",
model: Songs
});
songsView.render();
as you can see I have this function: onSongAdded
we have some built-in events such as add that get 3 arguments like this:
add(collection, model , options)
how can I use these arguments in my code?
can you help me?

el option is for pointing the view to an element already existing in DOM. Your item views should be creating new <li> elements so you should be using tagName option instead.
In your collection view constructor you've defined el option and you're passing a different el option while instantiating it. If #songs is a <uL> in DOM, then no use in defining el: "ul", in constructor.
Also, there is no need to manually instantiate models, you can just pass objects into collections and collection will do it internally. And don't pass collection as model, pass it as collection.

Related

Passing Backbone Model attribute to Handlebars Helper

The Backbone model has the attribute "selectedYear". I need to pass this "selectedYear" attribute to Handlebars Custom Helper.
var sq2SelectCarYearModel = Backbone.Model.extend({
urlRoot: "api/caryears",
selectedYear: "0"
});
Here is what I have tried:
This is the handlebars templating:
template: Handlebars.compile("{{#times 27 this.model.attributes.selectedYear}}{{/times}}")
Handlebars Helper declaration:
Handlebars.registerHelper('times', function(n, selectedYear, block) {
// I need to use "this.model.attributes.selectedYear" here
});
PS: "times" is the name of the custom helper, "n" is the number of times a loop will run.
I also tried this:
template: Handlebars.compile("{{#times 27 selectedYear}}{{/times}}")
but it still doesnt work.
selectedYear is not an attribute on your model, but a property.
You can set it as a default by doing:
var CarModel = Backbone.Model.extend({
urlRoot: 'api/caryears',
defaults: {
selectedYear: 0
}
});
var model = new CarModel()
// model.get('selectedYear') -> 0
you can also pass it in on instantiation
var model2 = new Model({ selectedYear: 2 });
// model2.get('selectedYear') -> 2
or you can set it after instantiation:
var model3 = new Model();
model3.set('selectedYear', 3);
// model3.get('selectedYear') -> 3
EDIT
To use the model attributes in a Backbone View I'd suggest doing something like the following
var MyView = Backbone.View.extend({
initialize: function() {
this.model = new Model({
selectedYear: 1
});
},
render: function() {
var template = Handlebars.compile("{{#times 27 selectedYear}}{{/times}}");
this.$el.html(template(this.model.toJSON));
}
});
Backbone.Marionette does a lot of this for you - if you give a Marionette View a template, it will automatically pass in the models attributes so you don't need to provide a render method.
eg:
var MyView = Marionette.ItemView.extend({
template: Handlebars.compile('your template here')
});
var model = new Model({selectedYear: 1});
var view = new view({model: model});
view.render();
// or region.show(view) which will automatically render the view.
You should set the selectedYear in model's defaults:
var sq2SelectCarYearModel = Backbone.Model.extend({
urlRoot: "api/caryears",
defaults: {
selectedYear: "0"
}
});
So that it'll be added to models attributes property. For setting it after creation, you should use set() method which will add the properties to models attribute hash.
right now, it's added as a direct property in model, this.model.selectedYear might work, but not the correct way to do it. Data should be added in models attributes hash so that other things like events work properly

Destroy() doesn't work properly

I'm writing basic to-do list using Backbone.js. Every input adding as a model to collection. Listening for 'add' on collection and rendering newly added model (appending li with 'task' to ul). Then by double-clicking on item I'm retrieving html() of it and in a loop comparing it to corresponding attribute in a model. When it catch the right model - destroying the model (should be deleted from a collection accordingly). But some issue occuring in console, it says
Uncaught TypeError: Cannot read property 'toJSON' of undefined
and adding some buggy effect (not everytime can delete item by the first dblckick). If anyone can point the problem out it would be greatly appreciated!
Here's code
var Model = Backbone.Model.extend({
default: {
task: '',
completed: false
}
});
var Collection = Backbone.Collection.extend({
model: Model
});
var ItemView = Backbone.View.extend({
tagName: 'li',
render: function () {
this.$el.html(this.model.toJSON().task);
return this;
}
});
var TodoView = Backbone.View.extend({
el: '#todo',
initialize: function () {
this.collection = new Collection();
this.collection.on('add', this.render, this);
},
events: {
'click .add': 'add',
'dblclick li': 'destroy',
'keydown': 'keyEvent'
},
add: function () {
this.collection.add(new Model({ //adding input as an model to collection
task: this.$el.find('#todo').val(),
completed: false
}));
this.$el.find('#todo').val(''); //clearing input field
this.$el.find('#todo').focus(); //focusing input after adding task
},
keyEvent: function (e) {
if (e.which === 13) {
this.add();
}
},
destroy: function (e) {
// console.log(this.collection.toJSON());
this.collection.each(function (model) {
if ($(e.target).html() === model.toJSON().task) {
model.destroy();
}
});
e.target.remove();
// console.log(this.collection.toJSON());
},
render: function (newModel) {
var self = this,
todoView;
todoView = new ItemView({
model: newModel
});
self.$el.find('.list').append(todoView.render().el);
return this;
}
});
var trigger = new TodoView();
And here's http://jsbin.com/ciwunizuyi/edit?html,js,output
The problem is that in your destroy method, you find the model to destroy by comparing the task property of the models. If you have multiple models with the same task property, you'll get the error. The actual error occurs because you're removing items from the collection while iterating over it.
Instead of comparing the task property, you could use the cid (client id) property that Backbone gives all models. One way to do this would be this:
When rendering an ItemView, use jQuery's data method to store the cid with the view element (alternatively, use a custom data attribute)
this.$el.data('cid', this.model.cid);
In the destroy function, get the cid property from the view element, and use it to find the right model in the collection (you can use the collection's get method here):
destroy: function (e) {
var id = $(e.target).data('cid');
var model = this.collection.get(id);
model.destroy();
e.target.remove();
},
Adding a unique attribute to the DOM element is only one way to solve this problem. One, much better, alternative would be to listen for the double-click event from the ItemView class itself. That way, you would always have a reference to this.model.
EDIT: This shows the code above in action: http://jsbin.com/nijikidewe/edit?js,output

Backbone console.log attributes and pass them to the View

I am not sure if I am using Models and Collections correctly. If I'm not I would really appreciate any guidance or advice into what I am doing wrong.
I have set up a Model and a Collection. The Collection has a url which is executed using the .fetch() method. I pass the Collection to the View where I log the results to the console. When I console.log(this.model) in the View I see the attributes nested a few levels deep. I would like to see the attributes in the console.log. The .toJSON() method doe not seem to work.
Here's a Fiddle to my current code: http://jsfiddle.net/Gacgc/
Here is the JS:
(function () {
var DimensionsModel = Backbone.Model.extend();
var setHeader = function (xhr) {
xhr.setRequestHeader('JsonStub-User-Key', '0bb5822a-58f7-41cc-b8a7-17b4a30cd9d7');
xhr.setRequestHeader('JsonStub-Project-Key', '9e508c89-b7ac-400d-b414-b7d0dd35a42a');
};
var DimensionsCollection = Backbone.Collection.extend({
model: DimensionsModel,
url: 'http://jsonstub.com/calltestdata'
});
var dimensionsCollection = new DimensionsCollection();
var DimensionsView = Backbone.View.extend({
el: '.js-container',
initialize: function (options) {
this.model.fetch({beforeSend: setHeader});
_.bindAll(this, 'render');
this.model.bind('reset', this.render());
return this;
},
template: _.template( $('#dimensions-template').html() ),
render: function () {
console.log( this.model.toJSON() ); //Why does this return an empty array???
return this;
}
});
var myView = new DimensionsView({model: dimensionsCollection});
}());
Is this what you're looking for?
If you're passing a collection to the view you should assign it to the collection property:
// It's a collection. Backbone views have a collection
// property. We should totally use that!
var myView = new DimensionsView({collection: dimensionsCollection});
When you attempt to bind the reset event to your view's render function, you're actually invoking the function immediately (by including the braces):
// Omit the braces to assign the function definition rather than invoke
// it directly (and immediately)
this.model.bind('reset', this.render);
But that's beside the point, because backbone's collection doesn't trigger a reset event (see documentation). One approach would be to assign the view's render function to the success parameter of the options object you pass to your collection:
var self = this;
this.collection.fetch({
beforeSend: setHeader,
success: function() {
self.render();
}
});
Finally, you need a parse function in your collection to pull the dimensions array out of the JSON you're loading:
var DimensionsCollection = Backbone.Collection.extend({
model: DimensionsModel,
url: 'http://jsonstub.com/calltestdata',
parse: function(response) {
return response.dimensions;
}
});

Retrieve Backbone Collection from Model and keep it as a Collection

I'm currently fooling around with backbone.js and came across some wierd behaviour trying to create some relationships between models and collections.
So here is my Model/Collection
Element = Backbone.Model.extend({
name: 'element'
});
Elements = Backbone.Collection.extend({
name: 'elements',
model: Element
});
Application = Backbone.Model.extend({
name: 'app',
initialize: function() {
this.elements = new Elements(this.get('elements'));
}
});
When I retrieve the elements via application.get('elements') I get a 'false' asking if this new Object is an instanceof Backbone.Collection.
var gotElements = application.get('elements');
var isCollection = gotElements instanceof Backbone.Collection;
So am I doing something wrong, or do I have to create a new Collection-Instance and fill it up with the Collection I receive from the application?
In your initialize function doing this.elements sets a property called 'elements' directly on your model (so model.elements will be your Backbone collection). The problem is when you try to retrieve this.elements by calling application.get('elements'), you will see it returns undefined (which is why it is not an instance of a Backbone collection).
In order for a model attribute to be retrievable using model.get it needs be set with model.set(attribute). If you examine the model in the console you will see the difference. model.set(myData) adds your data to the model's attributes hash. model.myData = myData adds a 'myData' property directly to the model.
To get this to work you can do the following:
Element = Backbone.Model.extend({
name: 'element'
});
Elements = Backbone.Collection.extend({
name: 'elements',
model: Element
});
Application = Backbone.Model.extend({
name: 'app',
elements: null
});
var application = new Application({
elements: new Elements()
});
var myElements = application.get('elements');
myElements should now be an empty Backbone Collection
Instead of putting your collection into another model, you should put it in the according view:
var ListView = new Backbone.View.extend({
initialize:function(){
this.Elements= new Elements();
// more stuff to go
},
render:function(){
_.forEach(this.Elements, function(){
//Do rendering stuff of indivdual elements and get HTML
});
//put HTML in the DOM
}
});
There is no need of a model containing a collection containing several models.
Edit: And instead of putting your app into a Model, you should put it into a view.

Backbone.js Persisting child variables to parent

What is the correct way to persist an inherited variable, on action to the parent in Backbone.js?
I can see some logical ways to do this but they seem inefficient and thought it might be worth asking for another opinion.
The two classes are both views which construct a new model to be saved to a collection, the parent passing a variable through to a popup window where this variable can be set.
I'm not sure there's enough detail in your question to answer, but there are a few ways to to do this:
Share a common model. As you describe it, you're using two views to construct a model, so the easiest way is probably to pass the model itself to the child view and have the child view modify the model, rather than passing any variables between views:
var MyModel = Backbone.Model.extend({});
var ParentView = Backbone.View.extend({
// initialize the new model
initialize: function() {
this.model = new MyModel();
},
// open the pop-up on click
events: {
'click #open_popup': 'openPopUp'
},
openPopUp: function() {
// pass the model
new PopUpView({ model: this.model })
}
});
var PopUpView = Backbone.View.extend({
events: {
'change input#someProperty': 'changeProperty'
},
changeProperty: function() {
var value = $('input#someProperty').val();
this.model.set({ someProperty : value });
}
});
Trigger an event on the parent. If for some reason you can't just pass the value via the model, you can just pass a reference to the parent and trigger an event:
var ParentView = Backbone.View.extend({
initialize: function() {
// bind callback to event
this.on('updateProperty', this.updateProperty, this);
},
updateProperty: function(value) {
// do whatever you need to do with the value here
},
// open the pop-up on click
events: {
'click #open_popup': 'openPopUp'
},
openPopUp: function() {
// pass the model
new PopUpView({ parent: this })
}
});
var PopUpView = Backbone.View.extend({
events: {
'change input#someProperty': 'changeProperty'
},
changeProperty: function() {
var value = $('input#someProperty').val();
this.options.parent.trigger('updateProperty', value);
}
});

Categories