Backbone 1.0 reset vs sync event - backbone.js

PgaPlayersApp.AppView = Backbone.View.extend({
el: '#pga_players_profile_app',
initialize: function()
{
//Should I do 1?
this.listenTo(PgaPlayersApp.Players, 'sync', this.addAll);
//Should I do 2?
this.listenTo(PgaPlayersApp.Players, 'reset', this.addAll);
PgaPlayersApp.Players.fetch({reset: true});
}
});
In the above code example, what is the preferred method for listening to a fetch for a collection? (sync or reset)

You should listen for 'sync'. This is the event fired on a successful fetch operation. A 'reset' is now only fired when an explicit collection.reset(newModels) is called. 'sync' is consistent between collections and models now, which is a nice consistency.
FYI: http://documentcloud.github.io/backbone/docs/backbone.html#section-93

Related

backbone.js level 2 challenge 5 codeschool answer

One example in codeschool's backbone.js tutorial has the following solution:
Application.js
var appointment = new Appointment({id: 1});
appointment.on('change',function() {
alert('its changed');
});
I realize this is probably a simplified example but in most cases wouldn't you want this defined on the model definition so it applies to all model instances?
Something in the model definition that says whenever an instance of me changes fire this method in the view? That view method could then fire the alert.
I'm obviously just learning so any help is appreciated!
Here the event is attached to that particular model instance. So the same will not trigger an event for any other instance..
var appointment = new Appointment({id: 1}); <--- Event is triggered
var appointment1 = new Appointment({id: 2}); <--- Event is not triggered
appointment.on('change',function() {
console.log('its changed');
});
Since the event is attached directly on the instance of the model. But if you do the same when defining the Model, it would trigger the same on all the instances of the Model.
var Appointment = Backbone.Model.extend({
initialize: function() {
this.on('change', function() {
console.log('its changed')
});
}
});
Now any change on the instance of the model will trigger an event.
var appointment = new Appointment({id: 1}); <--- Event is triggered
var appointment1 = new Appointment({id: 2}); <--- Event is triggered
If you talking about the same on a View, then the model that is passed to the instance will generally keep listening to the event. And if there is any change then a method will be invoked changing the state of the view.
var View = Backbone.View.extend({
initialize: function() {
// Listening to the event on the model which when
// triggered will render the view again
this.listenTo(this.model, 'change', this.render);
},
render: function() {
// do something
}
});
var view = new View();
view.render();

Is it possible to trigger an event when initializing a model?

In a backbone model, is it possible to trigger an event in the initialize function, for a nested view? I based my current code off this example: https://stackoverflow.com/a/8523075/2345124 and have updated it for backbone 1.0.0. Here is my initialize function, for a Model:
var Edit = Backbone.Model.extend({
initialize: function() {
this.trigger('marquee:add');
this.on('change', function(){
this.trigger('marquee:add');
});
}
...
}
I'm trying to call a method renderMarquee when the model is initialized:
var EditRow = Backbone.View.extend({
initialize: function() {
this.listenTo(this.model, "change", this.render); // works
this.listenTo(this.model, "marquee:add", this.renderMarquee); // only called when changed, but not when initially created
...
}
renderMarquee IS called when the model is changed, but not when it is initialized. 'change' events work as expected (this.render is called). Any thoughts?
Thanks!
I am currently facing a similar problem. I needed to trigger the change event in the initialize method of my model.
I looked into the backbone code which revealed why this is not happening:
var Model = Backbone.Model = function(attributes, options) {
...
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
};
the set is executed before the initialize and this.change is emptied setting the model state to "nothing has changed".
In order to overwrite behavior this I added the following code to my initialize method.
initialize: function(attributes, options) {
...
this.changed = attributes;
this.trigger('change');
for (attr_name in attributes) {
this.trigger('change:' + attr_name);
}
},
I trigger all change events manually, this is important for me since inheriting models may bind to change or change:attrxy. But this is not enough, because if I just trigger the events the changedAttributes() method would return false therefore I also set this.changed to the current attributes.
This doesn't make a lot of sense because you are initializing the model somewhere prior to doing the view.listenTo call. Unfortunately, you don't really have a choice in that matter.
You are probably going to want to move the event handling to a Backbone.Collection which already has built in events you can listen on for adding/removing.

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.

Backbone custom event trigger not being recognised?

I'm learning Backbone.js for the first time and I'm having an issue trying to get a custom event from triggering (or from the View from recognising when it's been triggered)?
You can see my Collection code here: https://github.com/Integralist/Backbone-Playground/blob/master/Assets/Scripts/App/main.js#L72-86 which when initialized it triggers a custom collection:init event.
var Contacts = Backbone.Collection.extend({
model: Contact,
initialize: function(){
this.trigger('collection:init');
this.bind('add', this.model_added, this);
},
model_added: function(){
console.log('A new model has been created so trigger an event for the View to update the <select> menu');
}
});
But later on in my View where I'm listening for that event I can't get the function populate to fire: https://github.com/Integralist/Backbone-Playground/blob/master/Assets/Scripts/App/main.js#L90-107
var ContactsView = Backbone.View.extend({
initialize: function(){
console.log(contacts.models, 'get initial model data and populate the select menu?');
},
events: {
'collection:init': 'populate',
'change select': 'displaySelected'
},
populate: function(){
console.log('populate the <select> with initial Model data');
},
displaySelected: function (event) {
console.log('get model data and display selected user', event);
}
});
Any ideas what I'm doing wrong?
The events hash in a view is used to bind events from the DOM to your view, e.g. events raised by the elements in your rendered view. To listen to events raised by your collection, you will have to set them manually:
var ContactsView = Backbone.View.extend({
initialize: function(){
contacts.on("collection:init",this.populate,this);
}
...
});
Note that you are using a global contacts variable, I would advise to use Backbone mechanisms and pass your collection to the constructor, as you do with the el:
var ContactsView = Backbone.View.extend({
initialize: function(){
console.log(this.collection.models);
this.collection.on("collection:init",this.populate,this);
}
...
});
var contacts_view = new ContactsView({
el: $('#view-contacts'),
collection:contacts
});
As #mu said in the comments, as is, your event won't do anything since you trigger it in the initialize method of the collection, which is automatically called by the constructor of the collection therefore before you can bind anything in the view. See this Fiddle to visualize the call order : http://jsfiddle.net/yRuCN/
Trigger it elsewhere, or, if I read correctly your intent, you (probably) want to use the built in reset event:
var ContactsView = Backbone.View.extend({
initialize: function(){
this.collection.on("reset",this.populate,this);
}
...
});
See http://jsfiddle.net/yRuCN/1/ for an example with potential uses.

Backbone.js: bind/unbind events across views

I am using the event aggregator pattern by Derick Bailey where he has illustrated the pattern in which an object manages the raising of events and the subscribers for those events.
It was all working fine where I was triggering events in one view and subscribing to them in other. The problem came when two or more views subscribe to an event and then at the time of discarding a view, one of the view unsubscribes from the event. This causes all the other views to be unsubscribed from the event as well.
Is there some workaround for this?
Update
Here is the a little bit of code that I'm using in my view:
var EventAggregator = _.extend({}, Backbone.Events);
new MyView({
collection: MyCollection,
eventagg: EventAggregator
});
MyView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render', 'close', 'actionFnc');
this.childviews = [];
this.options.eventagg.bind('evt:action', this.actionFnc);
this.render();
},
render: function() {
},
close: function() {
_(this.childViews).each(function(childview) {
childview.close();
});
$(this.el).empty();
this.options.eventagg.unbind('evt:action');
},
actionFnc: function() {
// do something over here
}
});
change the following line:
this.options.eventagg.unbind('evt:action');
to
this.options.eventagg.unbind('evt:action', this.actionFnc);

Resources