I would like to call a function when a "load" event is triggered:
events: {
"load #eventPicture" : "_resizeHeaderPic"
}
I don't want to do something like this.$("#eventPicture").on("load", _resizeHeaderPic); because I have a lot of views (it's a Single Page App) and I could go back to show another view before the image was loaded. So, if I then come back to this view I would have two listener for that "load" event. Right? By putting everything in my events hash, I can undelegate properly.
But it seems that "load #eventPicture" does not work. Any suggestion?
You cannot track load event from Backbone events because this event fires only on image instance and doesn't bubble. So Backbone.View's $el cannot track it.
jQuery callback on image load (even when the image is cached)
UPDATE
I would suggest to use another concept (JSFiddle). This is best practice:
var LayoutView = Backbone.View.extend({
el : '[data-container]',
show : function (view) {
// remove current view
this.$view && this.$view.remove();
// save link to the new view
this.$view = view;
// render new view and append to our element
this.$el.html(this.$view.render().el);
}
});
var ImageView = Backbone.View.extend({
template : _.template('<img src="https://fbcdn-sphotos-g-a.akamaihd.net/hphotos-ak-prn2/1375054_4823566966612_1010607077_n.jpg"/>'),
render : function () {
this.$el.html(this.template());
this.$('img').on('load', _.bind(this.onLoad, this));
return this;
},
onLoad : function () {
console.log('onLoad');
}
});
var OtherView = Backbone.View.extend({
template : _.template('lalala'),
render : function () {
this.$el.html(this.template());
return this;
}
});
var Router = Backbone.Router.extend({
routes : {
'other' : 'other',
'*any' : 'image'
},
initialize : function (options) {
this.layout = new LayoutView();
},
other : function () {
this.layout.show(new OtherView());
},
image : function () {
this.layout.show(new ImageView());
}
});
new Router();
Backbone.history.start();
Related
I have a view that contains two sub views, each with their own HTML template.
It works fine for what I have now. However, I now need an event to be fired from one subview to the other.
For example, when the user is in the Edit View, and they forget to click something(checkbox, radio button, or whatever), and they go back to the Display View, I want a warning to show up in that display view template(html) that warns them of the things they missed.
Is this possible? To pass events around like this between sibling views?
Thanks!
Here's the basic code structure I have now:
return Backbone.View.extend({
render: function(SubView) {
SubView = SubView || DisplayView;
this.view = new SubView({
model: this.model
});
this.$el.html(this.view.render().$el);
return this;
}
})
var DisplayView = Backbone.View.extend({
render: function() {
this.$el.html(this.template(this.model.toJSON()));
})
var EditView = Backbone.View.extend ({
toggleDisplay: function () {
this.checkAllItems();
},
checkAllItems: function() {
if (this.$('.engineParts').val().length > 0) {
this.render(DisplayView);
} else {
this.$('.awarning').css('display', 'block'); //warning class in DisplayView template.
this.render(DisplayView);
}
}
})
So I'm trying to learn how to use the backbone events using the documentation
but I'm stuck at the events part, when I click on the page class content it should alert "page tag has been clicked" but it throws an error on the commented line.
<body>
<div class="page"></div>
</body>
<script type="text/javascript">
var View = Backbone.View.extend({
initialize: function()
{
this.render();
},
render: function()
{
this.$el.html('Click me im an element');
},
events: function()
{
//Uncaught SyntaxError: Unexpected token :
"click .page" : "callme"
},
callme: function()
{
alert('page tag has been clicked');
}
});
var view = new View({
el: '.page'
});
</script>
Your events property must be either a hash
events: {
"click .page" : "callme"
}
or a function that returns a hash
events: function() {
return {
"click .page" : "callme"
};
}
You indicate a .page selector but that's your view element. Either use a global selector
events: {
"click " : "callme"
}
or set your el to an ancestor node, for example
var view = new View({
el: 'body'
});
The events is actually just an object it isn't a function. It'll work with the code below. Hope that helps.
events: {
"click .page" : "callme"
}
The other error you have is that you're not actually using the Backbone view.
You create the View correctly but you're not appending it to the view as far as I can tell.
You'd need to do something like.
$('body').html(view.render().el);
That will append your view to the DOM and add all of the event listeners.
Also instead of passing in the el to the BackboneView you could just add the class of page onto the View. Example below.
className: page,
You actually have two problems with your code, the first is that you are using a function for our events hash without returning an object (using a function is fine, but you need to return an object, or bind directly to the events hash). The second is that your are listing for an event for a child element with the page class, which doesn't exist. You want to either remove the class from where you are binding to the event and just listen to a click anywhere in your view, or listen to an existing element.
For example
var View = Backbone.View.extend({
initialize: function()
{
this.render();
},
render: function()
{
this.$el.html('Click me im an element');
},
events: {
"click" : "callme"
},
callme: function()
{
alert('page tag has been clicked');
}
});
var view = new View({
el: '.page'
});
http://jsbin.com/temicema/1/
That should be enough to get your code working, however it is probably worth understanding how backbone events work. When you specify an event in backbone that event is bound to the root el and and then listens to the events you specify matching the selector you specified. Under the hood backbone is basically using jQuery's .on to delegate the events, so in your case backbone is basically doing this.$el.on('click, '.page', this.callme).
I'm beginning with Backbone.js and trying to build my first sample app - shopping list.
My problem is when I fetch collection of items, reset event isn't probably fired, so my render method isn't called.
Model:
Item = Backbone.Model.extend({
urlRoot : '/api/items',
defaults : {
id : null,
title : null,
quantity : 0,
quantityType : null,
enabled : true
}
});
Collection:
ShoppingList = Backbone.Collection.extend({
model : Item,
url : '/api/items'
});
List view:
ShoppingListView = Backbone.View.extend({
el : jQuery('#shopping-list'),
initialize : function () {
this.listenTo(this.model, 'reset', this.render);
},
render : function (event) {
// console.log('THIS IS NEVER EXECUTED');
var self = this;
_.each(this.model.models, function (item) {
var itemView = new ShoppingListItemView({
model : item
});
jQuery(self.el).append(itemView.render().el);
});
return this;
}
});
List item view:
ShoppingListItemView = Backbone.View.extend({
tagName : 'li',
template : _.template(jQuery('#shopping-list-item').html()), // set template for item
render : function (event) {
jQuery(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
Router:
var AppRouter = Backbone.Router.extend({
routes : {
'' : 'show'
},
show : function () {
this.shoppingList = new ShoppingList();
this.shoppingListView = new ShoppingListView({
model : this.shoppingList
});
this.shoppingList.fetch(); // fetch collection from server
}
});
Application start:
var app = new AppRouter();
Backbone.history.start();
After page load, collection of items is correctly fetched from server but render method of ShoppingListView is never called. What I am doing wrong?
Here's your problem:
" When the model data returns from the server, it uses set to (intelligently) merge the fetched models, unless you pass {reset: true}" Backbone Docs
So, you want to fire the fetch with the reset option:
this.shoppingList.fetch({reset:true}); // fetch collection from server
As an aside, you can define a collection attribute on a view:
this.shoppingList = new ShoppingList();
this.shoppingListView = new ShoppingListView({
collection : this.shoppingList // instead of model: this.shoppingList
});
Are you using Backbone 1.0? If not, ignore this, otherwise, you may find what the doc says about the Collection#fetch method interesting.
To quote the changelog:
"Renamed Collection's "update" to set, for parallelism with the similar model.set(), and contrast with reset. It's now the default updating mechanism after a fetch. If you'd like to continue using "reset", pass {reset: true}"
So basically, you're not making a reset here but an update, therefore no reset event is fired.
I am having an application layout like the one attached. The upper panel is already to the page (i.e. in the server's HTML response). While the user interacts with the elements in that panel the content of the dynamic panel below changes accordingly.
I've studied Backbone Marionette various View types and Region Manager. But I still can't figure out a way to implement this. I need to capture events from the already rendered elements and change the dynamic content accordingly. As I understand, every time a region is created to show a specific Marionette view, the region's content is replaced by that view's el. And with that I cannot have a Layout view for the container of the whole thing.
So can this be done in anyway using Marionette?
You can certainly support what I would call a "pre rendered" or partial view. In fact, here's a Marionette View that I use quite a bit, as I'm working under with an app that includes server side partial views:
My.PartialView = Backbone.Marionette.Layout.extend({
render: function () {
//noop
if (this.onRender) {
this.onRender();
}
return this;
},
onShow: function () {
// make sure events are ready
this.delegateEvents();
}
});
It's simple to use:
My.NavBar = My.PartialView.extend({
events: {
"change #search-input": "searchRequested",
"click #faq-link": "faqRequested",
"click #home-link": "homeRequested",
},
searchRequested: function (e) {
// search
},
faqRequested: function (e) {
// show the faq
},
homeRequested:function () {
// go home
}
});
var navbar = new main.views.NavBar({ el: ".my-nav" });
someRegion.show();
// or, just wire up the events manually
navbar.delegateEvents();
I think the better way is using constructor.
Make your rendered layout class.
App.RenderedLayout = Marionette.Layout.extend({
render: function () {
if (this.onRender) {
this.onRender();
}
return this;
},
constructor: function(){
this._ensureElement();
this.bindUIElements();
Marionette.Layout.prototype.constructor.apply(this, slice(arguments));
}
});
Then you can use full of Marionette capabilities.
App.module('Some.Page', function (Mod, App, Backbone, Marionette, $, _) {
Mod.SomeLayout = App.RenderedLayout.extend({
el: '#renderedDiv',
events: {
'click .something': 'onSomethingClick'
},
regions: {
'innerRegion': '#innerRegion'
},
ui: {
something: '.something div'
},
initialize: function () {
},
onSomethingClick: function(e){
return false;
}
});
Mod.addInitializer(function(){
App.addRegions({renderedRegion: '#renderedDiv'});
Mod.someLayout = new Mod.SomeLayout();
App.renderedRegion.attachView(Mod.someLayout);
});
});
I have a BoardView containing a CellCollection of CellModels. I fetch the collection from the db and then create the CellViews.
This all works swimmingly until I try to access a CellModel via a click event on the BoardView. I can't get to the underlying models at all... only the views. Is there a way to do this?
I've attempted to include the relevant code below:
CellModel = Backbone.Model.extend({});
CellCollection = Backbone.Collection.extend({
model : CellModel
});
CellView = Backbone.View.extend({
className : 'cell',
});
BoardView = Backbone.View.extend({
this.model.cells = new CellCollection();
render : function() {
this.cellList = this.$('.cells');
return this;
},
allCells : function(cells) {
this.cellList.html('');
this.model.cells.each(this.addCell);
return this;
},
addCell : function(cell) {
var view = new Views.CellView({
model : cell
}).render();
this.cellList.append(view.el);
},
events : {
'click .cell' : 'analyzeCellClick',
},
analyzeCellClick : function(e) {
// ?????????
}
});
I need the click to "happen" on the BoardView, not the CellView, because it involves board-specific logic.
Good question! I think the best solution would be to implement an
EventBus aka EventDispatcher
to coordinate all events among the different areas of your application.
Going that route seems clean, loosely coupled, easy to implement, extendable and it is actually suggested by the backbone documentation, see Backbone Docs
Please also read more on the topic here and here because (even though I tried hard) my own explanation seems kind of mediocre to me.
Five step explanation:
Create an EventBus in your main or somewhere else as a util and include/require it
var dispatcher = _.clone(Backbone.Events); // or _.extends
Add one or more callback hanlder(s) to it
dispatcher.CELL_CLICK = 'cellClicked'
Add a trigger to the Eventlistener of your childView (here: the CellView)
dispatcher.trigger(dispatcher.CELL_CLICK , this.model);
Add a Listener to the Initialize function of your parentView (here: the BoardView)
eventBus.on(eventBus.CARD_CLICK, this.cardClick);
Define the corresponding Callback within of your parentView (and add it to your _.bindAll)
cellClicked: function(model) {
// do what you want with your data here
console.log(model.get('someFnOrAttribute')
}
I can think of at least two approaches you might use here:
Pass the BoardView to the CellView at initialization, and then handle the event in the CellView:
var CellView = Backbone.View.extend({
className : 'cell',
initialize: function(opts) {
this.parent = opts.parent
},
events : {
'click' : 'analyzeCellClick',
},
analyzeCellClick : function() {
// pass the relevant CellModel to the BoardView
this.parent.analyzeCellClick(this.model);
}
});
var BoardView = Backbone.View.extend({
// ...
addCell : function(cell) {
var view = new Views.CellView({
model : cell,
parent : this
}).render();
this.cellList.append(view.el);
},
analyzeCellClick : function(cell) {
// do something with cell
}
});
This would work, but I prefer to not have views call each other's methods, as it makes them more tightly coupled.
Attach the CellModel id to the DOM when you render it:
var CellView = Backbone.View.extend({
className : 'cell',
render: function() {
$(this.el).data('cellId', this.model.id)
// I assume you're doing other render stuff here as well
}
});
var BoardView = Backbone.View.extend({
// ...
analyzeCellClick : function(evt) {
var cellId = $(evt.target).data('cellId'),
cell = this.model.cells.get(cellId);
// do something with cell
}
});
This is probably a little cleaner, in that it avoids the tight coupling mentioned above, but I think either way would work.
I would let the CellView handle the click event, but it will just trigger a Backbone event:
var CellView = Backbone.View.extend({
className : 'cell',
initialize: function() {
_.bindAll(this, 'analyzeCellClick');
}
events : {
'click' : 'analyzeCellClick',
},
analyzeCellClick : function() {
this.trigger('cellClicked', this.model);
}
});
var BoardView = Backbone.View.extend({
// ...
addCell : function(cell) {
var view = new Views.CellView({
model : cell
}).render();
this.cellList.append(view.el);
view.bind('cellClicked', function(cell) {
this.analyzeCellClick(cell);
};
},
analyzeCellClick : function(cell) {
// do something with cell
}
});