Backbone.js Views not rendering - javascript

Something bizarre is going on. I have code which creates a Backbone.js View, except it never gets rendered, however if i run it in console it works:
function createBookingsView($container, roomID){
var BookingsView = Backbone.View.extend({
el : $container,
initialize : function(){
console.log("derp");
_.bindAll(this, "addOne", "addAll", "render");
this.bookings = new Bookings();
this.bookings.bind("change", this.addOne);
this.bookings.bind("refresh", this.addAll);
this.bookings.bind("all", this.render);
this.bookings.fetch({data : {"room" : roomID}});
console.log(this.bookings.get(1));
},
addAll : function(){
this.bookings.each(this.addOne);
},
addOne : function(booking){
var view = new BookingView({model:booking});
$(this.el).append(view.render().el);
},
render : function(){
$(this.el).html("");
this.addAll();
}
});
return new BookingsView;
};
and heres how it's called:
window.LEFT_BOOKINGS = createBookingsView($("#timetable-a .bookingContainer"), room.id);
when i manually run the above line in console, it works brilliantly. but it doesnt load in my script.

I just had some issues with Asynchronous functions not returning before I needed them.

Related

backbone paginator multi model in a view

I have a shopping cart app made with Backbone.Paginator.Fluenced and forked with this example; https://github.com/msurguy/laravel-backbone-pagination
I made some small changes;
when you click over an item link, it opens a bootstrap modal window.
The code is below.
app.views.ItemView = Backbone.View.extend({
tagName: 'div',
className: 'col-sm-4 col-lg-4 col-md-4',
template: _.template($('#ProductItemTemplate').html()),
events: {
'click a.openModal': 'openModal'
},
initialize: function() {
this.model.bind('change', this.render, this);
this.model.bind('remove', this.remove, this);
},
render : function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
openModal : function () {
var view = new app.views.ModalView({model:this.model});
view.render();
}
});
and this is my ModalView to show product details in a modal window.
app.views.ModalView = Backbone.View.extend({
template: _.template($('#modal-bsbb').html()),
initialize: function() {
_.bind(this.render, this);
},
render: function () {
$('#myModalPop').modal({backdrop: 'static',keyboard: true});
$('#myModalPop').html(this.template({
'model':this.model.toJSON()
}));
return this;
}
});
Everything is fine for above codes.
I decided to optimize this code and wanted some improvements on this.
Firstly I am fetching all product data and send these data to modal windows.
I think i must send only main meta data and must fetch details from these window.
So i made a new Backbone Model and Collection;
app.models.ItemDetails = Backbone.Model.extend({});
app.collections.ItemDetails = Backbone.Collection.extend({
model: app.models.ItemDetails,
dataType: 'json',
url : "/api/item-details",
parse: function(response){
return response.data;
}
});
My api returns JSON :
{"data":{"id":8,"title":"Product 8","seo":"product-8","code":"p8","review":"Lorem30"}}
My problem is adding multiple models to ModalView;
I tried a lot of example and questions in blogs&forums couldnt find any solve.
I tried a lot of things ($.extend, to set model and model vs..)
to change ModalView and below codes are last position of them;
app.views.ModalView = Backbone.View.extend({
template: _.template($('#modal-bsbb').html()),
initialize: function() {
_.bind(this.render, this);
},
render: function () {
var itemDetails = new app.collections.ItemDetails(); // this is new line
var model2 = itemDetails.fetch(); // this is new line
$('#myModalPop').modal({backdrop: 'static',keyboard: true});
$('#myModalPop').html(this.template({
'model1':this.model.toJSON(),
'model2':model2.model // this is new line
}));
return this;
}
});
I want to add a second model to my underscore template. But cant!
Firstly when i run below codes on chrome developer console it gets an Object;
but couldnt convert as a new model or JSON.
var itemDetails = new app.collections.ItemDetails();
var model2 = itemDetails.fetch();
console.log(model2); // gets fetch data as an object
I am afraid I am confused about where the problem exactly is.
Sorry guys I am not a backbone expert and probably I am doing something wrong though I searched a lot about it on the forum. I read about it again and again but I could not solve the problem. Could you please help me. Thank you in advance.
SOLVE:
After searchs and by the help of below reply.
I solved my problem.
app.views.ModalView = Backbone.View.extend({
template: _.template($('#modal-bsbb').html()),
initialize: function() {
_.bind(this.render, this);
},
render: function () {
var _thisView = this;
var itemsDetails = new app.collections.ItemsDetails();
itemsDetails.fetch({
success:function(data){
$('#myModalPop').modal({backdrop: 'static',keyboard: true})
.html(_thisView.template({
'model1':_thisView.model.toJSON(),
'model2':data.at(0).toJSON()
}));
}});
}
});
Every request to server using backbone is async, it means that you will not have the returned data immediately after the request, maybe the server still processing the data.
To solve this problem you have 2 ways.
First Way: Callbacks
Inside your Model/Collection
GetSomeData:->
#fetch(
success:=(data)>
console.log data // the returned data from server will be avaiable.
)
Second way: Listen for an trigger.
This one it's more elegant using backbone because you don't write callbacks.
Inside Model
GetSomeData:->
#fecth()
Inside View
initialize:->
#model = new KindOfModel()
#model.on "sync", #render, #
backbone automatically will trigger some events for you, take a read here.
http://backbonejs.org/#Events
As you're already doing, you'll need to listen to some trigger on the collection too
var itemDetails = new app.collections.ItemDetails(); // this is new line
var model2 = itemDetails.fetch(); // here is the problem

Page refresh binds backbone events twice

I have created an extensive app using Backbone. So far, everything works very well. However, when I refresh/reload a page on a given hash (e.g. myapp/#dashboard), the view is rendered twice and all events are bound twice. If I go to another section and come back. everything is working normally.
I use a subrouter that looks like this:
var DashboardRouter = Backbone.SubRoute.extend({
routes : {
/* matches http://yourserver.org/books */
"" : "show",
},
authorized : function() {
// CODE TO RETRIEVE CURRENT USER ID ...
return (lg);
},
show : function() {
var usr = this.authorized();
if (this.dashboardView) {
this.dashboardView.undelegateEvents();
}
switch(usr) {
case 2:
this.dashboardView = new StudentDashboard();
break;
case 3:
this.dashboardView = new CounsellorDashboard();
break;
case 4:
this.dashboardView = new AdminDashboard();
break;
default:
location.replace('#signout');
}
},
});
I have checked within the console, and the events here are called only once. The student dashboard looks like this (extract)
DashboardView = Backbone.View.extend({
el : "#maincontent",
template : tpl,
model : new Student(),
events : {
"click #edit-dashboard" : "editDashboard",
"click #add-grade" : "addGrade",
"click #add-test" : "addTest",
"click #add-eca" : "addECA"
},
initialize : function() {
// BIND EVENTS
_.bindAll(this, 'render', 'editDashboard', 'renderGrades', 'renderTests', 'renderECAs', 'renderPreferences');
this.model.on("change", this.render);
this.model.id = null;
this.model.fetch({
success : this.render
});
},
render : function() {
$(this.el).html(this.template(this.model.toJSON()));
// set location variables after main template is loaded on DOM
...
if (!this.gradeList) { this.renderGrades(); };
if (!this.testList) { this.renderTests(); };
if (!this.ecaList) { this.renderECAs(); };
if (!this.preferencesView) { this.renderPreferences(); };
this.delegateEvents();
return this;
},
From the console logs I know that all the subviews are rendered normally only once, but twice when I refresh the page, and I have no idea why.
You need to make sure all events on your view are undeligated before re-rendering it.
Add following function inside your views.
cleanup: function() {
this.undelegateEvents();
$(this.el).empty();
}
Now, in your router before rendering the view, do the cleanup if the view already exists.
if (this.myView) { this.myView.cleanup() };
this.myView = new views.myView();

Button in sub view is not working in main view of backbone js

I create one sign in view, and put it in other main views.
Here is one of a main view :
define(["jquery" ,
"underscore" ,
"backbone" ,
"webconfig",
"text!templates/header.html",
"text!templates/signInTemplate.html" ,
"text!templates/miniSignInTemplate.html",
"text!templates/footer.html"
],function($ , _ , Backbone, WebConfig, HeaderTem, SignInTem, MiniSignInTem, FooterTem){
var signInView = Backbone.View.extend({
initialize : function(){
},
el: '#webbodycontainer',
render : function(){
this.$el.empty();
var headerTem = _.template(HeaderTem);
var signInTem = _.template(SignInTem);
var miniSignInTem = _.template(MiniSignInTem);
var footerTem = _.template(FooterTem);
$("#webheader").html(headerTem);
this.$el.html(signInTem);
$("#rightpanel").html(miniSignInTem);
$("#webfooter").html(footerTem);
}
});
return signInView;
});
And here is a sub view :
define(["jquery" ,
"underscore" ,
"backbone" ,
"webconfig",
"text!templates/miniSigninTemplate.html"
],function($ , _ , Backbone , WebConfig , signinTemp){
var MiniView = Backbone.View.extend({
initialize:function(){
this.render();
},
event : {
'click #signIn' : 'signInUser'
},
signInUser : function(){
alert(1);
},
render:function(){
var template = _.template(signinTemp)
this.$el.html(template);
}
});
return MiniView;
});
Routing main view :
app_router.on('route:signInAction', function(signIn){
if(window.currentSection)
window.currentSection.remove();
window.currentSection = new SignIn({});
$("#webbodycontainer").html(window.currentSection.$el);
window.currentSection.render(signIn);
});
Problem : signInUser in sub view is not working also the whole view (MiniView) is not called. Did I miss something?
Any help would be much appreciated, thank you..
In what you have written here, you can render the view by doing something like this:
var singInView = new SignIn();
enter code heresingInView.render();
You will not need these lines:
window.currentSection = new SignIn({});
// unnecessary, just create a new object when needed
// plus, binding objects to window is totally not standard
$("#webbodycontainer").html(window.currentSection.$el);
// when you call render() on a new object, it binds it to the dom
// you do not need this line either
window.currentSection.render(signIn);
// why are you passing signIn to render? this doesn't do anything
In short, you can call your view and render it in a one liner (if you are not passing any other arguments to the view) like this:
(new SignIn()).render();
If you want to pass arguments to the view, again you can do it in a one liner:
(new SignIn({
key: value,
key: value
})).render();

backbone.js doesn't fire my events

I am writing a backbone.js app, and I have a problem.
My collections do not fire events, can anyone spot the problem in the code bellow? I get the render-feedback, the initializer feedback.. but the append method is never called. I know that the "../app" returns a list with tro json items. And I can even see that these are being created in the collection.
Why do my event not get called?
window.TablesInspectorView = Backbone.View.extend({
tagName: "div",
initialize: function () {
console.log('Initializing window.TablesInspectorView');
// setup the tables
this.data = new Backbone.Collection();
this.data.url = "../app";
this.data.fetch();
// some event binds..
this.data.on("change", this.render , this);
this.data.on("add" , this.append_item, this);
},
render: function(){
console.log("render");
_.each(this.data.models, this.append_item);
},
append_item: function(item) {
console.log("appended");
}
});
According to my knowledge , the backbone fetch() is an asynchronous event and when it completes the reset event is triggered ,
When the models belonging to the collection (this.data) are modified , the change event is triggered, so im guessing you have not got that part correct.
so i would do something like this :
window.TablesInspectorView = Backbone.View.extend({
tagName: "div",
initialize: function () {
console.log('Initializing window.TablesInspectorView');
// setup the tables
this.data = new Backbone.Collection();
this.data.url = "../app";
this.data.fetch();
// some event binds..
this.data.on("reset", this.render , this); //change here
this.data.on("add" , this.append_item, this); // i dont see a this.data.add() in you code so assuming this was never called ?
},
render: function(){
console.log("render");
_.each(this.data.models, this.append_item);
},
append_item: function(item) {
console.log("appended");
}
});

backbone.js model not firing events

I have a view which doesn't seem to want to render as the model's change event is not firing.
here's my model:
var LanguagePanelModel = Backbone.Model.extend({
name: "langpanel",
url: "/setlocale",
initialize: function(){
console.log("langselect initing")
}
})
here's my view:
var LanguagePanelView = Backbone.View.extend({
tagName: "div",
className: "langselect",
render: function(){
this.el.innerHTML = this.model.get("content");
console.log("render",this.model.get(0))
return this;
},
initialize : function(options) {
console.log("initializing",this.model)
_.bindAll(this, "render");
this.model.bind('change', this.render);
this.model.fetch(this.model.url);
}
});
here's how I instantiate them:
if(some stuff here)
{
lsm = new LanguagePanelModel();
lsv = new LanguagePanelView({model:lsm});
}
I get logs for the init but not for the render of the view?
Any ideas?
I guess it's about setting the attributes of the model - name is not a standard attribute and the way you've defined it, it seems to be accessible directly by using model.name and backbone doesn't allow that AFAIK. Here are the changes that work :) You can see the associated fiddle with it too :)
$(document).ready(function(){
var LanguagePanelModel = Backbone.Model.extend({
//adding custom attributes to defaults (with default values)
defaults: {
name: "langpanel",
content: "Some test content" //just 'cause there wasn't anything to fetch from the server
},
url: "/setlocale",
initialize: function(){
console.log("langselect initing"); //does get logged
}
});
var LanguagePanelView = Backbone.View.extend({
el: $('#somediv'), //added here directly so that content can be seen in the actual div
initialize : function(options) {
console.log("initializing",this.model);
_.bindAll(this, "render");
this.render(); //calling directly since 'change' won't be triggered
this.model.bind('change', this.render);
//this.model.fetch(this.model.url);
},
render: function(){
var c = this.model.get("content");
alert(c);
$(this.el).html(c); //for UI visibility
console.log("render",this.model.get(0)); //does get logged :)
return this;
}
});
var lpm = new LanguagePanelModel();
var lpv = new LanguagePanelView({model:lpm});
}); //end ready
UPDATE:
You don't need to manually trigger the change event - think of it as bad practice. Here's what the backbone documentation says (note: fetch also triggers change!)
Fetch
model.fetch([options])
Resets the model's state from the server.
Useful if the model has never been populated with data, or if you'd
like to ensure that you have the latest server state. A "change" event
will be triggered if the server's state differs from the current
attributes. Accepts success and error callbacks in the options hash,
which are passed (model, response) as arguments.
So, if the value fetched from the server is different from the defaults the change event will be fired so you needn't do it yourself. If you really wish to have such an event then you can use the trigger approach but custom name it since it's specific to your application. You are basically trying to overload the event so to speak. Totally fine, but just a thought.
Change
model.change()
Manually trigger the "change" event. If you've been
passing {silent: true} to the set function in order to aggregate rapid
changes to a model, you'll want to call model.change() when you're all
finished.
The change event is to be manually triggered only if you've been suppressing the event by passing silent:true as an argument to the set method of the model.
You may also want to look at 'has changed' and other events from the backbone doc.
EDIT Forgot to add the updated fiddle for the above example - you can see that the alert box pops up twice when the model is changed by explicitly calling set - the same would happen on fetching too. And hence the comment on the fact that you "may not" need to trigger 'change' manually as you are doing :)
The issue was resolved my adding
var LanguagePanelModel = Backbone.Model.extend({
//adding custom attributes to defaults (with default values)
defaults: {
name: "langpanel",
content: "no content",
rawdata: "no data"
},
events:{
//"refresh" : "parse"
},
url: "/setlocale",
initialize: function(){
log("langselect initing");
//this.fetch()
},
parse: function(response) {
this.rawdata = response;
// ... do some stuff
this.trigger('change',this) //<-- this is what was necessary
}
})
You don't need attributes to be predefined unlike PhD suggested. You need to pass the context to 'bind' - this.model.bind('change', this.render, this);
See working fiddle at http://jsfiddle.net/7LzTt/ or code below:
$(document).ready(function(){
var LanguagePanelModel = Backbone.Model.extend({
url: "/setlocale",
initialize: function(){
console.log("langselect initing");
}
});
var LanguagePanelView = Backbone.View.extend({
el: $('#somediv'),
initialize : function(options) {
console.log("initializing",this.model);
// _.bindAll(this, "render");
//this.render();
this.model.bind('change', this.render, this);
//this.model.fetch(this.model.url);
},
render: function(){
var c = this.model.get("content");
alert(c);
$(this.el).html(c);
console.log("render",this.model.get(0));
return this;
}
});
var lpm = new LanguagePanelModel();
var lpv = new LanguagePanelView({model:lpm});
lpm.set({content:"hello"});
}); //end ready

Categories