Issue related to rendering multiple views through a single view - backbone.js

Question Updated
I am implementing a search and result for the same in the same page. i
have two seperate html views and views for search and result.
Here is what is happening..
From my router the below view is loaded. This view will load two other views called search and result. I have included the respective html views in the seperate views. but when i run the proj, it displays nothing.
Am i rendering the view in this file wrong ??
if i am rendering it wrong can somebody please tell me where is the mistake and how to rectify it ??
should i include the respective html templates of search and result also in this file ??
views.driver.search.js :
define(
[ 'jquery',
'underscore',
'backbone',
'app/models/model.driver',
'app/collections/collection.driver',
'app/models/model.driver.searchform',
'app/dashboard/views.driver.searchForm',
'app/models/model.driver.searchresult',
'app/dashboard/views.driver.searchResults',
],
function ($, _, Backbone, DriverModel,SearchResultCollection ,searchFormModel, searchFormView, SearchResultModel,SearchResultView) {
var DriverSearchView = Backbone.View.extend({
el: $('#content'),
initialize: function(){
this.render();
},
render: function () {
// var compiledTemplate = _.template(searchFormTemplate, {});
// this.$el.html(compiledTemplate);
this.searchFormInitModel = new searchFormModel();
var searchformView = new searchFormView({model:this.searchFormInitModel});
this.$("#content").html(searchformView.render());
var driver1 = new DriverModel({id:1,firstName:"driver1",lastName:'last',dob:'12/12/12001',});
var driver2 = new DriverModel({id:2,firstName:"driver2",lastName:'last',dob:'12/12/12001',});
var driver3 = new DriverModel({id:3,firstName:"driver3",lastName:'last',dob:'12/12/12001',});
var driver4 = new DriverModel({id:4,firstName:"driver3",lastName:'last',dob:'12/12/12001',});
this.searchResultCollection= new SearchResultCollection([driver1, driver2, driver3, driver4]);
var searchResultView = new SearchResultView({el:this.$el.find("#searchResult"),collection:this.searchResultCollection});
this.$("#content").html(searchResultView.render());
//this.$el.find("#searchResult").html(searchResultView.render());
}
}); // Our module now returns our view
return DriverSearchView;
});

I don't see an issue with your workflow. Reason you are not seeing your console.logs, is because you are returning an object literal containing your initialize function without actually calling the function. Is there a reason you need to return an object from your initialize module?
Anyhow, I am not entirely sure how you calling your app.js file, but try the following if you do not need to return an object back from your initialize module
define(
[
'jquery',
'underscore',
'backbone',
'app/router',
// 'datatable'
],
function ($, _, backbone, router){ //,datatable) {
var initialize = (function () {
console.log("App1");
debugger;
console.log("App2");
router.initialize();
console.log("App3");
})();
// Depending what you want to do here, you could just
// console.log("Router initialized...");
// router.initialize();
});

Related

Why won't my model get passed?

I have this collection view
define([
'jquery',
'underscore',
'backbone',
'views/project',
'collections/project-collection',
'templates'
], function ($, _, Backbone, ProjectView, ProjectCollection, JST) {
'use strict';
var ProjectListView = Backbone.View.extend({
template: JST['app/scripts/templates/projectList.ejs'],
el: $('#content'),
render: function() {
var projectCollection = new ProjectCollection();
projectCollection.fetch();
projectCollection.each(this.addOne(),this);
return this;
},
addOne: function(project) {
console.log('addOne function');
var projectView = new ProjectView({model: project});
this.$el.html( projectView.render().el);
}
});
return ProjectListView;
});
No matter what I try the model never gets passed through to the addOne function so the in the view that is instantiated by this method the call to
this.model.toJSON()
results in the old 'cannot call method .toJSON of undefined' error. I tried to inject the collection when this collection view was instantiated and that didn't work either. Obviously here it is in the dependency array and that doesn't work either. The model is definitely there as I can log projectCollection.model to the console inside the render function. I'm stumped.
I see two problems with your render: one you know about and one you don't.
The first problem is right here:
projectCollection.each(this.addOne(), this);
The parentheses on this.addOne() call the addOne method right there rather than passing the this.addOne function to each as a callback. You want this:
projectCollection.each(this.addOne, this);
The second problem is that you have to wait for the collection's fetch to return before anything will be in the collection. You can use the fetch's callbacks:
var _this = this;
projectCollection.fetch({
success: function() {
projectCollection.each(_this.addOne, _this);
}
});
or you can use the various events that fetch will fire, see the fetch documentation for details.

RequireJS + BackboneJS - connect modules

I have a problem when I try to connect two modules containing two different views of BackboneJS.
In this module of RequireJS contains a view of backbone.
I need within this module, refer to another view of backbone that is in another module.
I modified the code to make it simpler
define (["jquery","backbone","collections/controlSearchCollection","views/currentPlaylist","jqueryUI"], function($, Backbone, controlSearchMusic, currentPlaylist){
var searchModule = Backbone.View.extend({
el: "#containerSearch",
initialize: function () {
this.collection = new controlSearchMusic();
},
events:{
"dblclick li":"select"
},
select: function(element){
var trackJSON ={};
trackJSON["id"]= "playCloud_"+$(element.target).attr("id");
currentPlaylist.collection.add(trackJSON); <--- Here is where this error
}
});
return searchModule;
});
Here, my other module of RequireJS containing a view of backboneJS. i need add to JSON from the first module.
define (["jquery","backbone","collections/controlCurrentPlaylistCollection","jqueryUI"], function($, Backbone, controlCurrentPlaylist){
var currentPlaylist = Backbone.View.extend({
el: "#currentPlaylist",
initialize: function(){
this.collection = new controlCurrentPlaylist();
this.collection.on("add", this.executeFunction, this);
},
executeFunction: function(song){
alert(song.toSource());
}
});
return currentPlaylist;
});
the two modules are instantiated in app.js
Someone can help me? Thanks you!
Without the exact error its hard to tell but it looks like you don't have created an instance of currentPlaylist. So currentPlaylist.collection is undefined and causing an error when your try to call the add function on it.
You can try this:
var cpl = new currentPlaylist(); // create instance
cpl.collection.add(trackJSON); // cpl.collection should be initialized here

Unable to reference Backbone model after model.set in Backbone View

I'm trying to get the view to self render by binding a change event to the views model. I've created a custom function on PageView which takes a model from the Pages collection as a paramater and uses this.model.set(data) to trigger the model change event. This is triggered when I pass it a Page model from the Pages collection in the AppView via this.page.load(Pages.at(index)). I'm running into a few problems though.
The change event is only fired once when switching back and forth between 2 different models, which I can resolve by running this.model.clear({silent:true}), but that's not ideal.
this.model is always undefined in any function other than the load() function within PageView which is really the main issue because I obviously can't fire this.render if the model is undefined. Hence the test:function().
Anyway here's the code for my AppView and PageView functions. Thanks in advance for any help.
define([
// These are path alias that we configured in our bootstrap
'jquery',
'underscore',
'backbone',
'handlebars',
'views/pageView',
'views/menuView',
'collections/pages'
], function($, _, Backbone, Handlebars,PageView,MenuView,Pages){
var AppView = Backbone.View.extend({
//Stores a reference to our main menu
mainMenu:{},
//Stores reference to current page
page:{},
//The parent div
el:'#app',
//Events that are being listened to on #app
events:{"click" : "active"},
//Process to run when this view is initialized
initialize:function(){
//Load our Pages Collection
Pages.reset(this.model.pages);
//Load the main menu
this.mainMenu = new MenuView;
this.mainMenu.model = this.model.main_menu;
this.mainMenu.render();
//Loads the page view
this.page = new PageView({model:Pages.at(0)});
},
//Currently just renders a page view with a designated model from the Pages collection
render:function(index){
this.page.load(Pages.at(index));
},
active:function(event){
$('.menu a').removeClass('active');
$('.menu a[href="' + event.target.hash + '"]').addClass('active');
}
});
return AppView;
// What we return here will be used by other modules
});
define([
// These are path alias that we configured in our bootstrap
'jquery',
'underscore',
'backbone',
'handlebars',
'text!templates/page.html',
], function($, _, Backbone, Handlebars, pageViewTemplate){
var PageView = Backbone.View.extend({
//Define the default template
template: Handlebars.compile(pageViewTemplate),
//The parent div for this element
el:'#content',
initialize:function(){
this.model.bind('change',this.test);
},
load:function(data){
this.model.set(data);
},
//Render function
render:function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
},
test:function(){
console.log(this.model);
console.log('change');
}
});
return PageView;
// What we return here will be used by other modules
});
does setting the context in your bind call fix things for you?
initialize:function(){
this.model.bind('change',this.test, this);
},

When is the right time to fetch a collection in Backbone js?

So I'm working on a backbone app, and trying to modularize things as much as I can using require.js. This has been my guide.
I'm having trouble getting my view to always fetch my collection. If I access my app from the base url (myapp.com/), and go to the route of my view, the collection is fetched. If I do not go to the view, and instead access it from myapp.com/#/campaigns, then the collection is not fetched.
Here is some relevant code.
router.js
define([
'jQuery',
'Underscore',
'Backbone',
'views/home/main',
'views/campaigns/list'
], function($, _, Backbone, mainHomeView, campaignListView ){
var AppRouter = Backbone.Router.extend({
routes: {
// Define some URL routes
'campaigns': 'showCampaigns',
// Default
'*actions': 'defaultAction'
},
showCampaigns: function(){
campaignListView.render();
},
defaultAction: function(actions){
// We have no matching route, lets display the home page
//mainHomeView.render();
}
});
var initialize = function(){
var app_router = new AppRouter;
Backbone.history.start();
};
return {
initialize: initialize
};
});
collections/campaigns.js
define([
'jQuery',
'Underscore',
'Backbone',
'models/campaigns'
], function($, _, Backbone, campaignsModel){
var campaignsCollection = Backbone.Collection.extend({
model: campaignsModel,
url: '/campaigns',
initialize: function(){
}
});
return new campaignsCollection;
});
views/campaigns/list.js
define([
'jQuery',
'Underscore',
'Backbone',
'collections/campaigns'
], function($, _, Backbone, campaignsCollection){
var campaignListView = Backbone.View.extend({
el:$('#container'),
initialize:function(){
this.collection = campaignsCollection;
this.collection.fetch();
},
render: function(){
var data = {
campaigns: this.collection,
_: _
};
$('#container').html('Campaigns length: '+data.campaigns.models.length);
}
});
return new campaignListView;
});
Any ideas on what I'm doing wrong? I believe it has something to do with calling this.collection.fetch() in the initalize function of the view. If that is the issue, where should I put fetch()?
The problem in your code is that your campaignListView fetch the collection when it is initialized and it is initialized only once. Your render method which is actually called from the router doesn't call your initialize method of campaignListView, when you change theurl your second time.
You have two options here :
1. return the class not the instance of your campaignListView and initialize it in the router :
// in your router code
showCampaigns: function(){
var campaignListViewInstance = new campaignListView(); // don't forget the brackets after your initialize function
campaignListViewInstance.render();
},
// in your campaignListView code :
return campaignListView; // without "new"
This will initialize the code everytime the router is hit.
2. place your fetch in the render method
// in your campaignListView code :
initialize:function(){
this.collection = campaignsCollection;
},
render: function(){
this.collection.fetch({success: function(collection) {
var data = {
campaigns: collection,
_: _
};
$('#container').html('Campaigns length: '+data.campaigns.models.length);
}); // this will be fetched everytime you render and also it has success callback
}
Also be aware that you should replace all your instance creating functions with brackets at the end
return new campaignListView; --> return new campaignListView();
return new campaignsCollection; --> return new campaignsCollection();
Another problem you will face is the async work of fetch. You should use success or event driven rendering of your collection, because fetch works in the background and you will have no data when you immediately call render after calling fetch.
+1 for your AMD approach.
I should really update the tutorial but it's better to not return instantiated modules. Maybe try checking out http://backboneboilerplate.com

Structuring my backbone.js application

I'm in the process of creating a Backbone.js app using Require.js. Each view file corresponds to one resource (e.g. 'News'). Within each view file, I declare a backbone
view for each action ('index', 'new', etc). At the bottom of the view file I receive
the necessary info from the router and then decide which view to instantiate (based on the info passed in from the router).
This all works well, but it requires lots of code and doesn't seem to be the 'backbone.js way'. For one thing, I'm rellying on the url to manage state. For another, I'm not using _.bind which pops up in a lot of backbone.js examples. In other words, I don't think I'm doing it right, and my code base smells... Any thoughts on how to structure my app better?
router.js
define([
'jquery',
'underscore',
'backbone',
'views/news'],
function($, _, Backbone, newsView){
var AppRouter = Backbone.Router.extend({
routes:{
'news':'news',
'news/:action':'news',
'news/:action/:id':'news'
},
news: function(action, id){
newsView(this, action, id).render();
}
});
var intialize = function(){
new AppRouter;
Backbone.history.start()
};
return{
initialize: initialize;
};
}
news.js ('views/news')
define([
'jquery',
'underscore',
'backbone',
'collections/news',
'text!templates/news/index.html',
'text!templates/news/form.html'
], function($, _, Backbone, newsCollection, newsIndexTemplate, newsFormTemplate){
var indexNewsView = Backbone.View.extend({
el: $("#content"),
initialize: function(router){
...
},
render: function(){
...
}
});
var newNewsView = Backbone.View.extend({
el: $("#modal"),
render: function(){
...
}
});
...
/*
* SUB ROUTER ACTIONS
*/
var defaultAction = function(router){
return new newsIndexView(router);
}
var subRouter = {
undefined: function(router){return defaultAction(router);},
'index': function(router){ return defaultAction(router);},
'new': function(){
return new newNewsView()
},
'create': function(router){
unsavedModel = {
title : $(".modal-body form input[name=title]").val(),
body : $(".modal-body form textarea").val()
};
return new createNewsView(router, unsavedModel);
},
'edit': function(router, id){
return new editNewsView(router, id);
},
'update': function(router, id){
unsavedModel = {
title : $(".modal-body form input[name=title]").val(),
body : $(".modal-body form textarea").val()
};
return new updateNewsView(router, id, unsavedModel);
},
}
return function(router, action, id){
var re = /^(index)$|^(edit)$|^(update)$|^(new)$|^(create)$/
if(action != undefined && !re.test(action)){
router.navigate('/news',true);
}
return subRouter[action](router, id);
}
});
While I feel like it's important to emphasize that there isn't really a "Backbone.js way", it does seem like you're replicating work Backbone should be doing for you.
I agree that it makes sense to have a specialized Router for each independent section of your application. But it looks at first glance like what you're doing in your "sub-router" section is just recreating the Backbone.Router functionality. Your AppRouter doesn't need to deal with /news URLs at all; you can just initialize a NewsRouter with news-specific routes, and it will deal with news-related URLs:
var NewsRouter = Backbone.Router.extend({
routes:{
'news': 'index',
'news/create': 'create',
'news/update/:id': 'update',
'news/edit/:id': 'edit'
},
index: function() { ... },
create: function() { ... },
// etc
});
As long as this is initialized before you call Backbone.history.start(), it will capture URL requests for its routes, and you never have to deal with the AppRouter. You also don't need to deal with the ugly bit of code at the bottom of your view - that's basically just doing what the core Backbone.Router does for you.
I'm using require.js and backbone as well I think the main difference that i'd suggest is that each file should return just one view, model, router or collection.
so my main html page requires my main router. That router is a module that requires a few views based on each of it's routes, and a bootstrapped model. Each router method passes the relevant bootstrapped model piece to the relevant view.
From there it stays really clean as long as each file is just 1 backbone thing (model, collection, view, router) and requires just the elements it uses. This makes for a lot of js files (I have about 100 for my current project) but that's where require.js optimization comes into play.
I hope that helps.
Why don't you structure your routes like this:
routes:{
'news':'news',
'news/edit/:id':'editNews',
'news/new':'newNews',
...
}

Resources