Backbone collection 0.9.9 - add event not work - backbone.js

Backbone collection 0.9.9 - add event not work
After update backbone to 0.9.9, i have a problem with (add).
(function () {
var Model = Backbone.Model.extend({
initialize: function () {
console.log('initialize Model');
}
});
var Collection = Backbone.Collection.extend({
model: Model,
url: "/json.json",
initialize: function () {
console.log('initialize Collection');
}
});
var View = Backbone.View.extend({
initialize: function () {
console.log('initialize View');
}
});
var collection = new Collection([
{
"id" : "001",
"name" : "Дарья",
"text" : "1 Вопрос - Ответ 1"
}
]);
collection.on('add', function () {
console.log('edd event', this)
});
collection.fetch({
add: true,
//silent: false,
success: function (model) {
console.log('fetch')
}
});
}());
console.log('edd event', this) - not work (
in old versions it works

It would appear that the add option to collection.fetch is no longer supported.
From 0.9.2 source (collection.fetch):
collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
From 0.9.9 source (collection.fetch):
var method = options.update ? 'update' : 'reset';
collection[method](resp, options);
if (success) success(collection, resp, options);
So by default collection.fetch will cause a reset on the collection, and the resetevent will be fired. If you pass option update:true, and update will be performed.
According to documentation for the new collection.update method, update will trigger the add events for added models, so the following should work:
collection.fetch({
update: true,
success: function (model) {
console.log('fetch')
}
});
Just test and be aware, that the new update method will also trigger remove and changeevents, if models are removed or changed.

You need to remove the commented out line because it won't propagate the add events otherwise (see line 827 of the backbone.js source). So the following should work
collection.fetch({
add: true,
silent: false,
success: function (model) {
console.log('fetch')
}
});
I'm not sure if that's a change from previous versions :)

From what I gather from checking out the Backbone 0.9.9 source, the add -option does nothing with fetch unless you add in the update - option as well. source
So to do something useful with it do the following:
collection.fetch({
add: true,
update: true, // this is necessary as well
//silent: false,
success: function (model) {
console.log('fetch')
}
});
This is also the cause for your problem. When you fetch, the Collection automatically defaults to the reset -function after fetching. reset silences the add -events and opts to just trigger a reset event as is evident from the Backbone.js source
if (models) this.add(models, _.extend({silent: true}, options));
So use the update option if you want the add -events and do not want to empty the collection before adding the new models. If you must have the reset functionality AND the add event, then you might have to write some custom implementation of reset.

Related

Backbone on('add') not being called

I defined the add handler on my collection:
var BookmarksCollection = Backbone.Collection.extend({
initialize: function() {
this.on('add', function(obj) {
console.log(obj.get('title') + ' added');
});
},
url: '/bookmarks',
model: Bookmark
});
And it's being called from one of my views:
var AddView = Backbone.View.extend({
el: $('#entry'),
events: {
'click #submit': 'submitHandler'
},
submitHandler: function(event) {
if($('input').val()) {
var newBookmark = new Bookmark;
newBookmark.set({url: $('input').val()});
console.log('Save!');
newBookmark.save({
success: function(newBookmark) {
console.log('Success!');
myBookmarks.add(newBookmark);
myBookmarks.trigger('add', newBookmark);
}
});
}
}
});
However the add handler on my collection is never triggered. In fact, not even the success function in the view seems to be called.
But the newBookmark gets saved anyway, so no errors happening.
What am I missing?
NodeJS respond with 201 (Created) when a new bookmark is posted.
Maybe backbone expects a 200 (OK) to trigger success?
EDIT: I tried triggering the event from outside the success function and it works.
How can I tweak backbone to react to a 201 (Created)?
I think the issue is that he first argument of save should be the data you are trying to save. The second is the options which can include the success and error callbacks.
newBookmark.save({dataiwanttosave: "hi"}, {
success: function(newBookmark) {
console.log('Success!');
myBookmarks.add(newBookmark);
myBookmarks.trigger('add', newBookmark);
}
});

backbone.js - When i change the name attribute nothing is updated and changed function not triggers [duplicate]

In my backbone function, while the name get change the change function not at all triggering.. any one suggest me the right way to get it.. (actually i need to get changed stuff and need to update);
code :
(function($){
var list = {};
list.model = Backbone.Model.extend({
defaults:{
name:'need the name'
},
initialize:function(){
this.bind('change:name', function(model) {
console.log('Model->change()', model);
});
}
});
list.collect = Backbone.Collection.extend({
model:list.model,
url : 'data/names.json',
initialize:function(){
this.fetch({update:true});
this.keepUpdate();
},
keepUpdate:function(){
var that = this;
var updateData = function(){
that.fetch({update:true});
myTimeout = setTimeout(updateData,10000);
}
var myTimeout = setTimeout(updateData,10000);
}
});
list.view = Backbone.View.extend({
initialize:function(){
this.collection = new list.collect();
this.collection.on("update", this.render, this);
this.collection.bind("change:name", function(model, attributes){
console.log(model,attributes,'property changed'); // this is not triggering at all..
});
},
render:function(data){
_.each(this.collection.models, function(data){
//console.log(data.get('name')); it works fine
})
},
updateName:function(){
console.log('updated called');
}
});
var newView = new list.view();
})(jQuery)
Collection.fetch doesn't trigger the change event. You only get the reset event. If you need more granular events, consider calling fetch with the options {update:true}.
that.fetch({update:true});
That will trigger change event for every model that was already in the collection, and add if the model was previously not in the collection.
Try removing keepUpdate from the collection and put a setTimeout in the initialize function of the view at the end. I suggest that fetch is called from the view as well as this.collection.fetch() instead of the collection's initialize function. Makes your code more reusable.
I'm not sure I understand your question. What are you trying to achieve ?
I don't think that fetch accepts {add:true} as a parameter (I just checked the source code and it does not appear anywhere).
When fetch completes, it only triggers a reset event (not an add). You should listen to that if you want to do something when the content of the collection changes. You can also simplify listen to change.

Right way for wiring backbone views

I have a two views:
1 LeftView (maximized when RightView is minimized & vice versa)
2 RightView (containing)
- collection of
- RightItemView (rendering RightItemModel)
When RightView is maximized and the user clicks a RightItemView, I want to maximize LeftView and display something according to the data from the clicked RightItemView.
What's the proper way to wire them?
I would recommend using the Backbone.Events module:
http://backbonejs.org/#Events
Basically, this line is all it takes to create your event dispatcher:
var dispatcher = _.clone(Backbone.Events);
Then all of your views can trigger/listen for events using the global dispatcher.
So, in RightItemView you would do something like this in the click event:
dispatcher.trigger('rightItemClick', data); // data is whatever you need the LeftView to know
Then, in LeftView's initialize function, you can listen for the event and call your relevant function:
dispatcher.on('rightItemClick', this.maximizeAndDisplayData);
Assuming your LeftView would have a function like so:
maximizeAndDisplayData: function(data) {
// do whatever you need to here
// data is what you passed with the event
}
The solution #jordanj77 mentioned is definitely one of the correct ways to achieve your requirement. Just out of curiosity, I thought of another way to achieve the same effect. Instead of using a separate EventDispatcher to communicate between the two views, why shouldn't we use the underlying model as our EventDispatcher? Let's try to think in those lines.
To start with, add a new boolean attribute to the RightItem model called current and default it to false. Whenever, the user selects the RightItemView, set the model's current attribute to true. This will trigger a change:current event on the model.
var RightItem = Backbone.Model.extend({
defaults: {
current: false,
}
});
var RightItemView = Backbone.View.extend({
events: {
'click li': 'changeCurrent'
}
changeCurrent: function() {
this.model.set('current', true);
}
});
On the other side, the LeftView will be handed a Backbone.Collection of RightItem models during creation time. You would anyways have this instance to supply the RightView isn't it? In its initialize method, the LeftView will listen for change:current event. When the event occurs, LeftView will change the current attribute of the model it is currently displaying to false and start displaying the new model that triggered this event.
var LeftView = Backbone.View.extend({
initialize: function() {
this.collection.on('change:current', this.render, this);
},
render: function(model) {
// Avoid events triggered when resetting model to false
if(model.get('current') === true) {
// Reset the currently displayed model
if (this.model) {
this.model.set('current') = false;
}
// Set the currently selected model to the view
this.model = model;
// Display the view for the current model
}
}
});
var leftView = new LeftView({
// Use the collection that you may have given the RightView anyways
collection: rightItemCollection
});
This way, we get to use the underlying model as the means of communication between the Left and Right Views instead of using an EventDispatcher to broker for us.
The solution given by #Ganeshji inspired me to make a live example
I've created 2 views for this.
var RightView = Backbone.View.extend({
el: $('.right_view'),
template: _.template('<p>Right View</p>'),
renderTemplate: function () {
this.$el.html('');
this.$el.append(this.template());
this.$link = this.$el.append('Item to view').children('#left_view_max');
},
events: {
'click #left_view_max' : 'maxLeftView'
},
maxLeftView: function () {
//triggering the event for the leftView
lView.trigger('displayDataInLeftView', this.$link.attr('title'));
},
initialize: function (options) {
this.renderTemplate();
}
});
var LeftView = Backbone.View.extend({
el: $('.left_view'),
template: _.template('<p>Left View</p>'),
renderTemplate: function () {
this.$el.html('');
this.$el.append(this.template());
},
displayDataInLeftView: function (data) {
this.$el.append('<p>' + data + '</p>');
},
initialize: function (options) {
//set the trigger callback
this.on('displayDataInLeftView', this.displayDataInLeftView, this);
this.renderTemplate();
}
});
var lView = new LeftView();
var rView = new RightView();
Hope this helps.

Additional Model is undefined

I am having problems including an additional model into my view which is based on a collection. I have a list of comments which is created by a parent view. Its need that I have the current user name when rendering the comments to show delete button and to highlight if its his own comment. The problem is now that I cant access in CommentListView the model session, so this.session in initialize or a call from a method like addAllCommentTo list is undefinied. What I am doing wrong here? I thought its easily possible to add another object to an view appart from the model.
CommentListView:
window.CommentListView = Backbone.View.extend({
el: $("#comments"),
initialize: function () {
this.model.bind('reset', this.addAllCommentToList, this);
this.model.bind('add', this.refresh, this);
this.model.bind('remove', this.refresh, this);
},
refresh: function(){
this.model.fetch();
},
addCommentToList : function(comment) {
console.log("comment added to dom");
//need to check why el reference is not working
$("#comments").append(new CommentView({model:comment, sessionModel: this.session}).render().el);
},
addAllCommentToList: function() {
$("#comments").empty();
this.model.each(this.addCommentToList);
}
});
Call from parent list in initialize method:
window.UserDetailView = Backbone.View.extend({
events: {
"click #newComment" : "newComment"
},
initialize: function () {
this.commentText = $("#commentText", this.el);
new CommentListView({ model: this.model.comments, session: this.model.session });
new LikeView({ model: this.model.like });
this.model.comments.fetch();
},
newComment : function() {
console.log("new comment");
this.model.comments.create(
new Comment({text: this.commentText.val()}), {wait: true}
);
this.commentText.val('');
}
});
Model:
window.UserDetail = Backbone.Model.extend({
urlRoot:'/api/details',
initialize:function () {
this.comments = new Comments();
this.comments.url = "/api/details/" + this.id + "/comments";
this.like = new Like();
this.like.url = "/api/details/" + this.id + "/likes";
this.session = new Session();
},
...
});
I see one problem, but can there be others.
You are initializing the View like this:
new CommentListView({ model: this.model.comments, session: this.model.session });
And you are expecting into your View to have a reference like this this.session.
This is not gonna happen. All the hash you send to the View constructor will be stored into this.options, from Backbone View constructor docs:
When creating a new View, the options you pass are attached to the view as this.options, for future reference.
So you can start changing this line:
$("#comments").append(new CommentView({model:comment, sessionModel: this.session}).render().el);
by this other:
$("#comments").append(new CommentView({model:comment, sessionModel: this.options.session}).render().el);
Try and tell us.
Updated
Also change this line:
this.model.each(this.addCommentToList);
by this:
this.model.each(this.addCommentToList, this);
The second argument is the context, in other words: what you want to be this in the called handler.

backbone router and collection issue

I have a collection and I need to access a model in the collection when a route is fired:
App.Houses = Backbone.Collection.extend({
model: App.House,
url: API_URL,
})
App.houseCollection = new App.Houses()
App.houseCollection.fetch();
App.HouseDetailRouter = Backbone.Router.extend({
routes: {
'': 'main',
'details/:id': 'details',
},
initialize: function() {
},
main: function() {
App.Events.trigger('show_main_view');
},
details: function(id) {
model = App.houseCollection.get(id);
console.log(model);
App.Events.trigger('show_house', model);
},
});
The result of that console.log(model) is undefined. I think that this is the case because the collection has not finished the fetch() call?
I want to attach the model to the event that I am firing so that the views that respond to the event can utilize it. I might be taking a bad approach, I am not sure.
One of the views that responds to the event:
App.HouseDetailView = Backbone.View.extend({
el: '.house-details-area',
initialize: function() {
this.template = _.template($('#house-details-template').html());
App.Events.on('show_house', this.render, this);
App.Events.on('show_main_view', this.hide, this);
},
events: {
'click .btn-close': 'hide',
},
render: function(model) {
var html = this.template({model:model.toJSON()});
$(this.el).html(html);
$(this.el).show();
},
hide: function() {
$(this.el).hide();
App.detailsRouter.navigate('/', true);
}
});
EDIT: Somewhat hacky fix: See details()
App.HouseDetailRouter = Backbone.Router.extend({
routes: {
'': 'main',
'details/:id': 'details',
},
initialize: function() {
},
main: function() {
App.Events.trigger('show_main_view');
},
details: function(id) {
if (App.houseCollection.models.length === 0) {
// if we are browsing to website.com/#details/:id
// directly, and the collection has not finished fetch(),
// we fetch the model.
model = new App.House();
model.id = id;
model.fetch({
success: function(data) {
App.Events.trigger('show_house', data);
}
});
} else {
// if we are getting to website.com/#details after browsing
// to website.com, the collection is already populated.
model = App.houseCollection.get(id);
App.Events.trigger('show_house', model);
}
},
});
Since you are using neither the callbacks nor events to know when the collection's fetch call completes, perhaps fetching the collection is generating an error, or the model you want is not included in the server response, or you are routing to the view before fetch has completed.
As to your approach, here are some miscellaneous tips:
better to pass the model to the view in the view's constructor's options parameter. render() takes no arguments and I think it is unconventional to change that.
Always return this from render() in your views
You can move your this.template = _.template code to the object literal you pass to extend. This code only needs to be run once per app load, not for each individual view
For now the simplest thing may be to instantiate just a model and a view inside your details route function, call fetch on the specific model of interest, and use the success callback to know when to render the view.

Resources