Backbone nested view has events which are not triggering - javascript

Okay so I have a parent view which has a click event which renders a child view. Within this child view is a form which I'm trying to validate and then submit. So my parent view looks something like this:
var MapView = Backbone.View.extend({
el: '.body',
template: _.template(MapTemplate),
render: function() {
...
},
events: {
'click #log-pane-title': 'loadLogView'
},
loadLogView: function() {
var eventLogView = new EventLogView({
id: properties._id
});
eventLogView.render();
}
});
And my child view looks something like this:
var EventLogView = Backbone.View.extend({
el: '#eventlog',
logform: new NewLogForm({
template: _.template(AddLogTemplate),
model: new LogModel()
}).render(),
render: function() {
// Render the form
$("#addtolog").html(this.logform.el);
},
events: {
'submit #addlogentry': 'test'
},
test: function() {
alert('inside eventlogview');
return false;
}
});
The problem I'm facing is that test() never fires. For debugging purposes I made sure the submit event was even firing by putting:
$('#addlogentry').on('submit', function() {
alert( "submit firing" );
return false;
});
In render() of the EventLogView. That does actually trigger, so I'm not sure what's going on and why test() isn't triggering.

To avoid scoping issues all the events delegation are scoped to the views el in Backbone.
So your #addlogentry button should live inside your EventLogView el.
And your sanity check in the render should look something like this to mimic how Backbone works internally :
this.$el.on('submit', '#addlogentry', function() {
alert( "submit firing" );
return false;
});

Related

How listen to other model events from your model in backbone js?

I have a problem with backbone. I have two models: A and B
I need to listen to events in one model (for instance A), and then after the event has happened make changes in the view of model B and its view.
Does anyone have a fairly simple example how such functionality can be implemented in backbone?
var Model_A_View= Backbone.View.extend({
events: {
// some events;
"click" : "ok",
},
initialize: function () {
this.Model_A = new Model_A({ // });
}
var Model_B_View= Backbone.View.extend({
events: {
// some events;
},
initialize: function () {
this.Model_B = new Model_B({ // });
this.listenTo( model_A , "change: ok", this.dosomethingFunction());
}
dosomethingFunction: function () {
//dosomething
}
Your code hard to read, no code style, and some synax error.
However, you'd better create model outside of you view's initialize function, and pass the model as a para when new a view:
var modelA = new Model_A();
var viewA = new Model_A_View({
model: modelA
});
var modelB = new Model_B();
var viewB = new Model_B_View({
model: modelB
});
viewB.listenTo(modelA, "change:ok", viewB.dosomethingFunction);
As variant you can use The Backbone Events. Few simple steps, how you can do this.
1.Specify events global object:
window._vent = _.extend({}, Backbone.Events);
2.Specify event triggers in your view/model/collection. For example for your view:
var Model_A_View = Backbone.View.extend({
events: {
// some events;
"click" : "ok",
},
initialize: function() {
this.Model_A = new Model_A({});
},
ok: function() {
vent.trigger('model_A:update', this.model); //you can also send your model
}
});
3.Specify event listening in your Model_B:
var Model_B_View = Backbone.View.extend({
initialize: function() {
this.Model_B = new Model_B({});
vent.on('model_A:update', this.updateModel, this);
},
updateModel: function() {
//this function will be call after `model_A:update` event triggered
//do something with Model_B
}
});

Backbone: Navigate function not working

So for some reason navigate won't work in one of my views. I'm doing everything in one file for now, so that may be the problem. Also I know the code is horrible, I'm just messing around with backbone right now.
EDIT: I put a console.log() in MarketingPage's function route and it never gets called, so there must be something wrong with the view.
Also, this is the error I'm getting from chrome dev tools:
Error in event handler for 'undefined': IndexSizeError: DOM Exception 1 Error: Index or size was negative, or greater than the allowed value.
at P (chrome-extension://mgijmajocgfcbeboacabfgobmjgjcoja/content_js_min.js:16:142)
at null.<anonymous> (chrome-extension://mgijmajocgfcbeboacabfgobmjgjcoja/content_js_min.js:18:417)
at chrome-extension://mgijmajocgfcbeboacabfgobmjgjcoja/content_js_min.js:1:182
at miscellaneous_bindings:288:9
at chrome.Event.dispatchToListener (event_bindings:390:21)
at chrome.Event.dispatch_ (event_bindings:376:27)
at chrome.Event.dispatch (event_bindings:396:17)
at Object.chromeHidden.Port.dispatchOnMessage (miscellaneous_bindings:254:22)
Here's my code:
/*global public, $*/
window.public = {
Models: {},
Collections: {},
Views: {},
Routers: {
},
init: function () {
console.log('Hello from Backbone!');
}
};
var App = Backbone.Router.extend({
routes: {
'': 'index',
'register': 'route_register',
},
index: function(){
var marketing_page = new MarketingPage();
},
route_register: function(){
var register_view = new RegisterView();
}
});
window.app = new App();
var User = Backbone.Model.extend({
url: '/user',
defaults: {
email: '',
password: ''
}
});
var MarketingPage = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function(){
var template = _.template($("#marketing-page").html());
$('.search-box').after(template);
},
events: {
'dblclick': 'route'
},
route: function(e){
e.preventDefault();
console.log("In route");
window.app.navigate('register', {trigger: true});
this.remove();
}
});
var RegisterView = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function(){
var template = _.template($("#register-template").html());
$('.search-box').after(template);
}
});
$(document).ready(function () {
Backbone.history.start();
});
When I type host/#register into the browser directly, the register view gets rendered, but no matter what I do the click event won't seem to work...
Since the handler function route isn't being called, it's likely that the event delegation isn't working.
One thing to note is that the event handling that is set up in a Backbone View is scoped to only that view's el. I don't see where yours is set up explicitly, so it might be creating an empty div, then handling events inside that empty div (which you don't want).
One trick I use for quick prototypes is to set the view's el with a jQuery selector pointing to something that exists on the page already, then in the render, show it with a .show().
Since you're not really doing that, here's one thing you could try. What we're doing is setting the $el content and then calling delegateEvents to make sure that the events and handlers are being bound.
var MarketingPage = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function(){
this.$el.html(_.template($("#marketing-page").html()));
$('.search-box').after(this.$el);
this.delegateEvents();
},
events: {
'dblclick': 'route'
},
route: function(e){
e.preventDefault();
console.log("In route");
window.app.navigate('register', {trigger: true});
this.remove();
}
});
Backbone.js views delegateEvents do not get bound (sometimes)
http://backbonejs.org/#View-delegateEvents

Backbone LayoutManager Re-Render SubViews

I'm using BBB with the great LayoutManager for the views.
Unfortunately, i can't find a way to re-render specific subviews. Here is my setting:
Home.Views.Layout = Backbone.Layout.extend({
template: "home/home",
el: "#main",
views: {
"#left-menu-container": new Home.Views.Leftmenu(),
"#searchbox": new Home.Views.Searchbox(),
"#content": new Home.Views.Content()
}
});
Home.HomeView = new Home.Views.Layout();
Home.HomeView.render();
Home.Views.AddEditPatient = Backbone.View.extend({
template: "......",
events: {
'click .dosomething': 'dosomething'
},
dosomething: function(){
// [dosomething]
// Only Render Sub-View, e.g. #content here...
}
});
I don't want to re-render the whole layout, what would be possible by calling Home.HomeView.render() again, but how can i render only the sub-view in this setting?
I think you want to add to do something like this with backbone.layoutmanager
thisLayout.setView("#content", new View()).render();
The backbone.layoutmanager v0.6.6 documentation might be helpful
http://documentup.com/tbranyen/backbone.layoutmanager/#usage/nested-views
Also check
http://vimeo.com/32765088
If I understand your question correctly, you can do this in your dosomething function:
this.$("#divToRenderTo").html(new subView().render().$el);
Be sure to have "return this;" at the end of your sub-view's render function.
There are two ways I generally do this with layoutmanager:
Instantiate views in your initialize function and then drop them into the view in beforeRender. This gives your view access to the subview so you can render it directly.
initialize: function() {
this.subview = new SubView();
},
beforeRender: function() {
this.insertView(this.subview);
},
doSomething: function() {
this.subview.render();
}
You can use view.getView(#selector) to return the embedded view and then call render on that.
doSomething: function() {
this.getView('#content').render();
}

Trigger function on click if View has a certain class (backbone.js)

I have a div generated by a backbone.js view. When the user clicks on this div, a class active is added to the div and the function addToSet is executed.
Problem: I want another function to be triggered when the View's div has the class active. However, my attempt shown below always cause addToSet function to run when its clicked.
Now, I remove 'click': 'addToSet' from the events function, leaving only 'click .active': 'removeFromSet'. Clicking on the div does not cause anything to happen! Is this because the event handler cannot select the div of the view itself, just the elements inside it?
Any idea how I can solve this problem? Thanks!
JS Code
SetView = Backbone.View.extend({
tagName: 'div',
className: 'modal_addit_set',
template: _.template( $('#tpl_modal_addit_set').html() ),
events: {
'click': 'addToSet',
'click .active': 'removeFromSet'
},
initialize: function(opts) {
this.post_id = opts.post_id;
},
render: function() {
$(this.el).html( this.template( this.model.toJSON() ) );
if(this.model.get('already_added'))
$(this.el).addClass('active');
return this;
},
addToSet: function() {
$.post('api/add_to_set', {
post_id: this.post_id,
set_id: this.model.get('id'),
user_id: $('#user_id').val()
});
},
removeFromSet: function() {
$.post('api/remove_from_set', {
post_id: this.post_id,
set_id: this.model.get('id')
});
}
});
Have you tried to use a :not(.active) selector for one of your event delegates? This may help differentiate between the two scenarios.
Something like this:
events: {
'click :not(.active)' : callback1
'click .active' : callback2
}
These events:
events: {
'click': 'addToSet',
'click .active': 'removeFromSet'
}
don't work and you sort of know why. From the fine manual:
Events are written in the format {"event selector": "callback"}. The callback may be either the name of a method on the view, or a direct function body. Omitting the selector causes the event to be bound to the view's root element (this.el).
So your 'click': 'addToSet' binds addToSet to a click on the view's el itself but 'click .active': 'removeFromSet' binds removeFromSet to a .active element inside the view's el.
I think the easiest solution is to have a single event:
events: {
'click': 'toggleInSet'
}
and then:
toggleInSet: function() {
if(this.$el.hasClass('active')) {
$.post('api/remove_from_set', {
post_id: this.post_id,
set_id: this.model.get('id')
});
}
else {
$.post('api/add_to_set', {
post_id: this.post_id,
set_id: this.model.get('id'),
user_id: $('#user_id').val()
});
}
}
You could use an instance variable instead of a CSS class to control the branching in toggleInSet if that makes more sense.

Getting the attribute from a View's Model when the view is clicked (backbone.js)

When a user clicks on a div with class .photo_container which is part of the view PhotoListView, there is a function sendSelectedPhotoId that will be triggered. This function has to get the attribute photo_id from the Photo model that belongs to this view whose div .photo_container element has been clicked, and send it to the serverside via fetch().
Problem: So far I managed to get the function sendSelectedPhotoId to be triggered when the div is clicked, but I cant figure out how to get the photo_id attribute of the view's Photo model. How should I achieve this?
On a side note, I'm not sure whether the correct photo_id will be send.
Code
$('#button').click( function() {
// Retrieve photos
this.photoList = new PhotoCollection();
var self = this;
this.photoList.fetch({
success: function() {
self.photoListView = new PhotoListView({ model: self.photoList });
$('#photo_list').html(self.photoListView.render().el);
}
});
});
Model & Collection
// Models
Photo = Backbone.Model.extend({
defaults: {
photo_id: ''
}
});
// Collections
PhotoCollection = Backbone.Collection.extend({
model: Photo,
url: 'splash/process_profiling_img'
});
Views
// Views
PhotoListView = Backbone.View.extend({
tagName: 'div',
events: {
'click .photo_container': 'sendSelectedPhotoId'
},
initialize: function() {
this.model.bind('reset', this.render, this);
this.model.bind('add', function(photo) {
$(this.el).append(new PhotoListItemView({ model: photo }).render().el);
}, this);
},
render: function() {
_.each(this.model.models, function(photo) {
$(this.el).append(new PhotoListItemView({ model: photo }).render().el);
}, this);
return this;
},
sendSelectedPhotoId: function() {
var self = this;
console.log(self.model.get('photo_id'));
self.model.fetch({
data: { chosen_photo: self.model.get('photo_id')},
processData: true,
success: function() {
}});
}
});
PhotoListItemView = Backbone.View.extend({
tagName: 'div',
className: 'photo_box',
template: _.template($('#tpl-PhotoListItemView').html()),
initialize: function() {
this.model.bind('change', this.render, this);
this.model.bind('destroy', this.close, this);
},
render: function() {
$(this.el).html(this.template( this.model.toJSON() ));
return this;
},
close: function() {
$(this.el).unbind();
$(this.el).remove();
}
});
SECOND ATTEMPT
I also tried placing the event handler and sendSelectedPhotoId in the PhotoListItemView where I managed to get the Model's attribute properly, but I can't figure out how to trigger the reset event when the PhotoList collection did a fetch().
View
PhotoListItemView = Backbone.View.extend({
tagName: 'div',
className: 'photo_box',
events: {
'click .photo_container': 'sendSelectedPhotoId'
},
template: _.template($('#tpl-PhotoListItemView').html()),
initialize: function() {
this.model.bind('change', this.render, this);
this.model.bind('destroy', this.close, this);
},
render: function() {
$(this.el).html(this.template( this.model.toJSON() ));
return this;
},
close: function() {
$(this.el).unbind();
$(this.el).remove();
},
sendSelectedPhotoId: function() {
console.log('clicked!');
var self = this;
console.log(self.model.get('photo_id'));
self.model.fetch({
data: { chosen_photo: self.model.get('photo_id')},
processData: true,
success: function() {
$(this.el).html('');
}});
}
});
Problem: With this, I cant seem to fire the reset event of the model after doing the fetch() in function sendSelectedPhotoId, which means I cant get it to re-render using PhotoListView's render().
In the screenshot below from Chrome's javascript console, I printed out the collection after sendSelectedPhotoId did its fetch(), and it seems like the fetched added the new data to the existing model, instead of creating 2 new models and removing all existing model!
You already have child views for each model, so I would put the click event handler in the child view. In the handler in the child, trigger an event passing this.model, and listen for that event in your parent.
Update based on update:
Try changing
this.model.bind('reset', this.render, this); to
this.model.bind('remove', this.render, this); // model is a collection right?
and then remove the model from the collection after the view is clicked. Also, I don't think using Model.fetch is what you really want to do. Maybe a .save or a custom method on the model?
Update based on author's comment showing sample base from blog
I would not follow that blog's advice. If you are using backbone professionally I can't recommend the Thoughtbot ebook enough.
It's $50 for a work in progress, and it's worth every penny
It has a simple sample application that lays out how to organize a backbone app. This is why I bought the book.
It uses Rails in the examples for the backend, but I have used Rails, Node, and C# MVC and all work no problem.

Categories