define events in Backbone.Model
var Todo = Backbone.Model.extend({
initialize: function(){
this.on('change', function(){
console.log('- Values for this model have changed.');
});
}
})
define events in Backbone.View
var TodoView = Backbone.View.extend({
className: "document-row",
events: {
"click .icon": "open",
"click .button.delete": "destroy"
}
})
My Question
define events syntax are quite different between model/collection and view, why are they designed in that way?
I think it's better to define model event like this. But backbone don't support it.
var Todo = Backbone.Model.extend({
events: {
"change": "foo"
},
foo: function(){
console.log("test")
}
});
There are two separate type of events: Backbone.Events and jQuery DOM events - so making these look the same seems like a bad idea as it would make code confusing not to mention it wouldn't actually work because the View UI events need different info: '<eventName> <optional DOM selector>: <methodName>' whereas normal internal events have a different syntax.
Backbone.Events follows the typical "publish/subscribe" pattern - it's just a way for apps to internally say "Something has happened" via .trigger and "I want to know when something happens" via .on or .once and the equivalent which you would use in a View because it handles cleaning up the listen when the view is removed: .listenTo and .listenToOnce.
So in your example the "change" event in the model is an internal event which Backbone fires when an attribute changes. The "change" in the View is jQuery DOM event (actually a delegate event) and you could optionally listen to something deeper in the view "change .myinput" so they are not equivalent.
The other difference is that .trigger can pass any arguments it likes after the first one (the event name), whereas the View event passes the DOM event object which you don't control e.g. onChange: function(ev) { ev.preventDefault(); }.
Related
I bind some events in backbone view and in this.destoryview() method, i called this.unbind(). But it not unbinding events. When some event happaned it called bounded method twice.
Then i change this.unbind() call by this.$el.unbind(), then it working properly.
events:{
'click #closeButton' : 'clearSearch',
// some events
},
initialize: function(options){
this.container = options.container;
},
render: function() {
if(this.oSearchContext.isAdvancedSearchEnabled() == true)
{
this.$el.html(this.advancedSearchSummaryViewTemplate);
}
else
{
this.$el.html(this.advancedSearchTemplate);
}
this.container.append(this.$el);
},
destroyView method with this.unbind()
destroyView : function()
{
if ( this.oAdvancedSearchSummaryView )
this.oAdvancedSearchSummaryView.destroyView();
if ( this.oAdvancedSearchDetailsView )
this.oAdvancedSearchDetailsView.destroyView();
// unbind all events
this.unbind(); // this.$el.unbind() working perfectly
// empty the rendered element
this.$el.empty();
}
Can you please explain me about differnce between both methods.
You use view.bind (or the modern view.listenTo or view.on) in order to subscribe to another backbone component such as listening to a change event in a backbone model.
You use view.$el.bind (or the modern view.$el.on) in order to listen to user interaction in the DOM.
Same logic applies to unbind or the modern off
Similar syntax and API, different purpose.
Instead of using bind I'd suggest to use Backbone's listenTo:
view.listenTo(model, 'change', view.render);
Once the view is destroyed, all the bindings will be automatically removed (unbinded);
I am trying to better structure my events in backbone. Currently I have one view communicating with another by triggering events within a function, and listening for events in another function, like:
//childView
triggerFilterChange: function(e){
Backbone.trigger('filterChange',activeFilters);
}
//parentView
initialize: function(){
Backbone.on('filterChange', this.onFilterChange, this);
},
onFilterChange:function(filters){
//DO STUFF
}
This works, however, I would like to make it more clear in my child view what events should be expected, rather than just triggering something from a random function somewhere buried within the view. For example, all of my click events for the child view are clearly delineated at the top of the page:
define([
'jquery',
'underscore',
'backbone',
], function($, _, Backbone){
var ProductsFiltersView = Backbone.View.extend({
events : {
"click .filter-options-container" : "filterOptionContainerClick",
"click .filter-option" : "filterOptionClick",
},
So my question is, is there a way to put custom events into this events object? Or some structure similar to this, so you know at the top of the view what events might be triggered? Like:
events : {
"click .filter-options-container" : "filterOptionContainerClick",
"click .filter-option" : "filterOptionClick",
"filterChange" : "doFilterChange"
},
doFilterChange: function(){
Backbone.trigger('parentFilterChange',activeFilters);
}
I wouldn't touch the events object for this anyhow.
The event object defines the events from child elements of el that are propagated to the parent element (el).
The question is more about how you glue different views together.
I use intermediary custom objects (which I call controllers, as Backbone does not provide Controllers out of the box) that are used to instantiate the views and listen to events that were triggered from within the view.
You can use specified event aggregators to use within particular 'controller' objects to handle the events.
MyApp = {};
MyApp.some_vent = _.extend({}, Backbone.Events);
MyApp.some_vent.on("some:event", function(){
alert("some event was fired!");
});
If the controller holds a reference to the view where you want to cause some effect, you can execute these view's methods accordingly.
No, it is not possible.
The event hash is parsed and event handlers are set by Backbone.View.prototype.delegateEvents.
delegateEvents uses selectors and method names from events, to bind delegated jQuery (or compatible library, like Zepto) event listeners on the view's DOM element:
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
Therefore you cannot use Backbone.View.prototype.event to listen to non-DOM events (or, indeed, DOM events from outside the view's element), without overriding Backbone.View.prototype.delegateEvents with your own implementation.
As an aside, your example code is flawed - triggering filterChange would result in an infinite loop.
in backbone we have an app that uses an event Aggregator, located on the window.App.Events
now, in many views, we bind to that aggregator, and i manually wrote a destroy function on a view, which handles unbinding from that event aggregator and then removing the view. (instead of directly removing the view).
now, there were certain models where we needed this functionality as well, but i can't figure out how to tackle it.
certain models need to bind to certain events, but maybe i'm mistaken but if we delete a model from a collection it stays in memory due to these bindings to the event aggregator which are still in place.
there isn't really a remove function on a model, like a view has.
so how would i tacke this?
EDIT
on request, some code example.
App = {
Events: _.extend({}, Backbone.Events)
};
var User = Backbone.Model.extend({
initialize: function(){
_.bindAll(this, 'hide');
App.Events.bind('burglar-enters-the-building', this.hide);
},
hide: function(burglarName){
this.set({'isHidden': true});
console.warn("%s is hiding... because %s entered the house", this.get('name'), burglarName);
}
});
var Users = Backbone.Collection.extend({
model: User
});
var House = Backbone.Model.extend({
initialize: function(){
this.set({'inhabitants': new Users()});
},
evacuate: function(){
this.get('inhabitants').reset();
}
});
$(function(){
var myHouse = new House({});
myHouse.get('inhabitants').reset([{id: 1, name: 'John'}, {id: 1, name: 'Jane'}]);
console.log('currently living in the house: ', myHouse.get('inhabitants').toJSON());
App.Events.trigger('burglar-enters-the-building', 'burglar1');
myHouse.evacuate();
console.log('currently living in the house: ', myHouse.get('inhabitants').toJSON());
App.Events.trigger('burglar-enters-the-building', 'burglar2');
});
view this code in action on jsFiddle (output in the console): http://jsfiddle.net/saelfaer/szvFY/1/
as you can see, i don't bind to the events on the model, but to an event aggregator.
unbinding events from the model itself, is not necessary because if it's removed nobody will ever trigger an event on it again. but the eventAggregator is always in place, for the ease of passing events through the entire app.
the code example shows, that even when they are removed from the collection, they don't live in the house anymore, but still execute the hide command when a burglar enters the house.
I see that even when the binding event direction is this way Object1 -> listening -> Object2 it has to be removed in order to Object1 lost any alive reference.
And seeing that listening to the Model remove event is not a solution due it is not called in a Collection.reset() call then we have two solutions:
1. Overwrite normal Collection cleanUp
As #dira sais here you can overwrite Collection._removeReference to make a more proper cleaning of the method.
I don't like this solutions for two reasons:
I don't like to overwrite a method that has to call super after it.
I don't like to overwrite private methods
2. Over-wrapping your Collection.reset() calls
Wich is the opposite: instead of adding deeper functionality, add upper functionality.
Then instead of calling Collection.reset() directly you can call an implementation that cleanUp the models before been silently removed:
cleanUp: function( data ){
this.each( function( model ) { model.unlink(); } );
this.reset( data );
}
A sorter version of your code can looks like this:
AppEvents = {};
_.extend(AppEvents, Backbone.Events)
var User = Backbone.Model.extend({
initialize: function(){
AppEvents.on('my_event', this.listen, this);
},
listen: function(){
console.log("%s still listening...", this.get('name'));
},
unlink: function(){
AppEvents.off( null, null, this );
}
});
var Users = Backbone.Collection.extend({
model: User,
cleanUp: function( data ){
this.each( function( model ) { model.unlink(); } );
this.reset( data );
}
});
// testing
var users = new Users([{name: 'John'}]);
console.log('users.size: ', users.size()); // 1
AppEvents.trigger('my_event'); // John still listening...
users.cleanUp();
console.log('users.size: ', users.size()); // 0
AppEvents.trigger('my_event'); // (nothing)
Check the jsFiddle.
Update: Verification that the Model is removed after remove the binding-event link
First thing we verify that Object1 listening to an event in Object2 creates a link in the direction Obect2 -> Object1:
In the above image we see as the Model (#314019) is not only retained by the users collection but also for the AppEvents object which is observing. Looks like the event linking for a programmer perspective is Object that listen -> to -> Object that is listened but in fact is completely the opposite: Object that is listened -> to -> Object that is listening.
Now if we use the Collection.reset() to empty the Collection we see as the users link has been removed but the AppEvents link remains:
The users link has disappear and also the link OurModel.collection what I think is part of the Collection._removeReference() job.
When we use our Collection.cleanUp() method the object disappear from the memory, I can't make the Chrome.profile tool to explicitly telling me the object #314019 has been removed but I can see that it is not anymore among the memory objects.
I think the clean references process is a tricky part of Backbone.
When you remove a Model from a Collection the Collection takes care to unbind any event on the Model that the Collection its self is binding. Check this private Collection method.
Maybe you can use such a same technique in your Aggregator:
// ... Aggregator code
the_model.on( "remove", this.unlinkModel, this );
// ... more Aggregator code
unlinkModel: function( model ){
model.off( null, null, this );
}
This is in the case the direction of the binding is Aggregator -> Model. If the direction is the opposite I don't think you have to make any cleaning after Model removed.
Instead of wrapping Collection's reset with cleanUp as fguillen suggested, I prefer extending Collection and overriding reset directly. The reason is that
cleanUp takes effect only in client's code, but not in library(i.e. Backbone)'s.
For example, Collection.fetch may internally call Collection.reset. Unless modifying the Backbone's source code, we cannot unbind models from events(as in cleanUp) after calling Collection.fetch.
Basically, my suggested snippet is as follows:
var MyCollection = Backbone.Collection.extend({
reset: function(models, options) {
this.each(function(model) {
model.unlink(); // same as fguillen's code
});
Backbone.Collection.prototype.reset.apply(this, arguments);
}
});
Later, we can create new collections based on MyCollection.
I have a backbone app with a view structure that looks like the following - note that I've removed implementations, models, collections, etc. for brevity:
NewsListView = Backbone.View.extend({
el: $('li#newspane'),
// This is what I would like to be able to do
// events: { 'filtered': 'reset' }
initialize: function() {
_.bindAll(this);
},
render: function() {
},
reset: function(){
}
});
FilterView = Backbone.View.extend({
el: $('li.filter'),
initialize: function() {
},
render: function() {
},
toggleFilter: function() {
}
});
AllView = Backbone.View.extend({
initialize: function() {
this.newsListView = new NewsListView();
this.filterView = new FilterView();
}
});
Essentially, whenever the FilterView's toggleFilter() function is called, I would like to fire off an event called filtered or something like that that is then caught by the NewsListView, which then calls its reset() function. Without passing a reference of a NewsListView object to my FilterView, I'm not sure how to send it an event. Any ideas?
You're on the right track. It sounds like what you need is a global event dispatcher. There a decent article and example here: http://www.michikono.com/2012/01/11/adding-a-centralized-event-dispatcher-on-backbone-js/
You might be able to do this using the already available functionality of jquery events and the backbone events property.
For example, instead of doing this from inside your subview:
this.trigger("yourevent", this);
do this instead:
this.$el.trigger("yourevent", this);
Then in any view that is a parent, grandparent, etc of your child view, listen for the event on that view's $el by defining a property on that view's events object:
events:{
"yourevent":"yourhandler"
}
and define the handler on that view as well:
yourhandler:function(subview) {
}
So this way, a view doesn't need to know about what descendant views exist, only the type of event it is interested in. If the view originating the event is destroyed, nothing needs to change on the ancestor view. If the ancestor view is destroyed, Backbone will detach the handlers automatically.
Caveat: I haven't actually tried this out yet, so there may be a gotcha in there somewhere.
You should check out the Backbone.Courier plugin as bubbling events is a perfect use case:
https://github.com/dgbeck/backbone.courier
The easiest way I've found to trigger and listen to events is to just use the Backbone object itself. It already has the events functions mixed in to it, so you can just trigger eg:
Backbone.trigger('view:eventname',{extra_thing:whatever, thing2:whatever2});
then, in any other backbone view in your app, you can listen for this event eg:
Backbone.on('view:eventname', function(passed_obj) {
console.log(passed_obj.extra_thing);
});
I'm not exactly sure what the advantage is in not using the Backbone object as your event handler, and instead creating a separate object to do it, but for quick-and-dirty work, the above works fine. HTH!
NOTE: one disadvantage to this is that every listener will "hear" every single event triggered in this way. Not sure what the big O is on that, but work being careful to not overload your views with lots of this stuff. Again: this is quick and dirty! :)
This problem can be solved using small backbone.js hack. Simply modify Backbone.Events.trigger for passing events to the this.parent
if this.parent != null
So, I came up a with a solution - create an object that extends Backbone.Events, and pass it as a parameter to multiple views. This almost feels like message passing between actors, or something. Anyway - I'm posting this as an answer in case anybody else needs a quick solution, but I'm not going to accept the answer. This feels hacky. I'd still like to see a better solution.
NewsListView = Backbone.View.extend({
el: $('li#newspane'),
// Too bad this doesn't work, it'd be really convenient
// events: { 'filtered': 'reset' }
initialize: function() {
_.bindAll(this);
// but at least this does
this.options.eventProxy.bind('filtered', this.reset);
},
render: function() {},
reset: function() {}
});
FilterView = Backbone.View.extend({
el: $('li.filter'),
initialize: function() {},
render: function() {},
toggleFilter: function() {
this.options.eventProxy.trigger('filtered');
}
});
AllView = Backbone.View.extend({
initialize: function() {
var eventProxy = {};
_.extend(eventProxy, Backbone.Events);
this.newsListView = new NewsListView({eventProxy: eventProxy});
this.filterView = new FilterView({eventProxy: eventProxy});
}
});
I'm pretty new to Backbone so excuse me if this question is a little obvious.
I am having problems with a collection inside of a model. When the collection changes it doesn't register as a change in the model (and doesn't save).
I have set up my model like so:
var Article = Backbone.Model.extend({
defaults: {
"emsID" : $('html').attr('id')
},
initialize: function() {
this.tags = new App.Collections.Tags();
},
url: '/editorial_dev.php/api/1/article/persist.json'
});
This works fine if I update the tags collection and manually save the model:
this.model.tags.add({p : "a"});
this.model.save();
But if the model is not saved the view doesn't notice the change. Can anyone see what I am doing wrong?
initialize: function() {
this.tags = new App.Collections.Tags();
var model = this;
this.tags.bind("change", function() {
model.save();
});
},
Bind to the change event on the inner collection and just manually call .save on your outer model.
This is actually an addendum to #Raynos answer, but it's long enough that I need answer-formatting instead of comment-formatting.
Clearly OP wants to bind to change and add here, but other people may want to bind to destroy as well. There may be other events (I'm not 100% familiar with all of them yet), so binding to all would cover all your bases.
remove also works instead of destroy. Note that both remove and destroy fire when a model is deleted--first destroy, then remove. This propagates up to the collection and reverses order: remove first, then destroy. E.g.
model event : destroy
model event : remove
collection event : destroy
collection event : remove
There's a gotcha with custom event handlers described in this blog post.
Summary: Model-level events should propagate up to their collection, but can be prevented if something handles the event first and calls event.stopPropagation. If the event handler returns false, this is a jQuery shortcut for event.stopPropagation();
event.preventDefault();
Calling this.bind in a model or collection refers to Underscore.js's bind, NOT jQuery/Zepto's. What's the difference? The biggest one I noticed is that you cannot specify multiple events in a single string with space-separation. E.g.
this.bind('event1 event2 ...', ...)
This code looks for the event called event1 event2 .... In jQuery, this would bind the callback to event1, event2, ... If you want to bind a function to multiple events, bind it to all or call bind once for each event. There is an issue filed on github for this, so this one will hopefully change. For now (11/17/2011), be wary of this.