BackboneJS - Router Functions - Calling Views? - javascript

I'm having an issue calling my views from with the router cfunctions besides within initialize.
this is my router code:
var ApplicationRouter = Backbone.Router.extend({
routes: {
"": "home",
//"*actions": "home",
"photo-gallery": "gallery",
"sound-lounge": "sound",
"contact": "contact"
},
initialize: function() {
this.homeView = new window.app.HomeView();
this.homeView.render();
/*
var soundView = new window.app.SoundView();
soundView.render();
var contactView = new window.app.ContactView();
contactView.render();
var galleryCollection = new window.app.GalleryCollection();
var gallery_items = galleryCollection.fetch();
gallery_items.done(function(){
var gallery_item = new GalleryView({ collection: galleryCollection });
});
*/
},
home: function() {
console.log('home');
},
sound: function() {
//var soundView = new window.app.SoundView();
//soundView.render();
console.log('sound');
},
contact: function() {
//var contactView = new window.app.ContactView();
// contactView.render();
console.log('contact');
},
gallery: function() {
console.log('gallery');
}
});
You can see able I have:
var soundView = new window.app.SoundView();
soundView.render();
commented out within the initalize function, this will work but as soon as I put it within the 'sound' function I get this error: Uncaught TypeError: undefined is not a function
It's to do with this part: new window.app.SoundView();
I have it called window.app.SoundView in my code, how do I go about getting this to work (it happens incorrectly for all my sections)
// ADDED soundView Code
// SOUNDVIEW
window.app.SoundView = Backbone.View.extend({
el: $("html"),
events: {
"click #sound-lounge": "render_sound"
},
initialize: function(){
this.render_sound();
},
render: function(model){
return this;
},
render_sound: function(){
this.model=new window.app.Home({id: 2});
var $main=this.$el.find('#content-area');
this.model.fetch().complete(function(data){
$main.html(data["responseJSON"].description);
});
}
});
Thanks

My problem ended up being as simple as removing window.app. from the soundView variable name.
e.g.
window.app.SoundView = Backbone.View.extend({ == SoundView = Backbone.View.extend({
AND
var soundView = new window.app.SoundView(); == var soundView = new SoundView();

Related

Are self instantiating views good practice or should I refactor?

I use a Backbone View to start my application using the code below. All it really does is encapsulate other objects I want to instantiate or load.
Is this O.K. or should I re-factor?
// App
//
//
//
var BVApp = Backbone.View.extend({
Name: 'BVApp',
el: window,
initialize: function () {
this.initIndependentConstructors();
this.initBBViews();
this.initComposite();
this.initBVArc();
},
initIndependentConstructors: function (){
new ImageLoader();
new SiteMorpher();
new AccountUpdater();
new SignOut();
},
initBBViews: function () {
new BVAccountExist();
new BVAccountCreator();
new BVAccountButton();
new BVAccountCode();
new BVFaveCreator();
},
initComposite: function () {
var token = ClientStorage.getToken();
this.CV = new BVComposite();
this.CV.renderCommon();
if (token) this.CV.render(token);
},
initBVArc: function () {
this.BVArcInstance = new BVArc({el: window, collection: new BCArc([], {data: {model: "ArcReader"}})});
}
});
var App = new BVApp();
}());

Backbone create a new view instance every request page

In my App i have created a View. this View is composed of a Template like a little Form. The Form has an button and in my View i create an click event to handle this button to create a new instance of another View passing the Form data to this View and put the data on html element. The problem is: if i enter in home route or in product 3 times and send a Form data, will appears 3 same Form datas.
Form view
window.userFormView = Backbone.View.extend({
el:$("#principal"),
events : {
'click .userButton' : 'newUser'
},
initialize:function(){
this.template = _.template($("#userFormView").html());
},
newUser : function(ev) {
ev.preventDefault();
//criamos uma nova instancia do model
window.user_view = new userViewes({model: users});
var u = { nome : $("#iName").val() ,sobrenome : $("#iLName").val() };
var user = new userModel(u);
users.add(user);
console.log(users);
return false;
},
render: function() {
this.$el.html("");
this.$el.html(this.template);
}
});
Form Template View
<script type="text/template" id="userFormView">
<form action="" id="form-new-user" class="formulario">
<span class="label">Name?</span><input type="text" id="iName" class="input">
<span class="label">Last Name?</span><input type="text" id="iLName" class="input">
<button class="userButton">Send</button>
<hr>
</form>
</script>
and my route are like this:
window.AppRouter = Backbone.Router.extend({
//
// Definindo rotas
//
routes: {
'home': 'index',
'product': 'productsList',
'foo1': 'doNothing1',
'foo2': 'doNothing2'
},
index: function () {
window.users = new userCollections();
window.userForm = new userFormView();
},
productsList : function() {
window.pCollection = new productCollections();
window.produtoForm = new produtoFormView();
},
doNothing1: function () {
console.log('doNothing1()');
},
doNothing2: function () {
console.log('doNothing2()');
}
});
window.router = new AppRouter();
Backbone.history.start();
userViewes view
window.userViewes = Backbone.View.extend({
// model: users,
el: $("#userContainer"),
initialize: function(){
this.model.on("add", this.render, this);
this.model.on("remove", this.render, this);
},
render: function() {
var self = this;
self.$el.html("");
this.model.each(function(user, indice) {
self.$el.append((new userView({model: user })).render().$el);
});
return this;
}
});
and finally userView:
window.userView = Backbone.View.extend({
//model: new userModel(),
tagName : 'div',
class : "userName",
events :{
'click .editar' : 'editar',
'click .remover' : 'remover',
'blur .sobrenome': 'fechar',
'keypress .sobrenome' : 'onEnterUpdate',
},
editar : function(ev) {
ev.preventDefault();
this.$('.sobrenome').attr('contenteditable', true).focus();
},
fechar : function(ev) {
var sobrenome = $(".sobrenome").text();
this.model.set("sobrenome", sobrenome);
$(".sobrenome").val();
this.$(".sobrenome").removeAttr("contenteditable");
},
onEnterUpdate : function(ev) {
var self = this;
if(ev.keyCode == 13) {
self.fechar();
_.delay(function(){
self.$(".sobrenome").blur();
}, 100);
}
},
remover : function(ev) {
ev.preventDefault();
window.users.remove(this.model);
},
initialize: function(){
this.template = _.template($("#userTemplate").html());
},
render : function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
When your view is using el option, make sure you clean up the existing view before you make a new one.
As it is, every time you switch between routes (without a full page refresh) a new instance pointing to same element is created which causes more and more event handlers to be bound to the el element which is in DOM, and the views stay in memory because of the binding. Try something like:
index: function () {
window.users = window.users || new userCollections();
if(window.userForm){
// clean up is important
window.userForm.remove();
}
window.userForm = new userFormView();
},
And of course, instead of repeating similar code in all routes, have a variable like this.currentView that points to the active view, and a common function that does necessary clean up
P.S: Adding properties to window object is a bad practice. Create your own name space or use the Router instance instead of window
I have found the answer. i implemented singleton pattern to get only one instance of the object. follow the code:
var single = (function(){
function createInstance() {
window.userForm = new userFormView();
window.users = new userCollections();
}
function users() {
return window.users;
}
function userForm() {
return window.userForm;
}
return {
init : function() {
if(!window.users && !window.userForm) {
createInstance();
}else{
this.render();
}
},
render: function() {
window.userForm.render();
}
}
}());
single.init();

How can i call function on view on the click event of Id, function is written on controller in backbone.js

My controller code is here.
spine.module("communityApp", function (communityApp, App, Backbone, Marionette, $, _) {
"use strict";
communityApp.Controllers.pforumController = Marionette.Controller.extend(
{
init: function(){
var func = _.bind(this._getpforum, this);
var request = App.request('alerts1:entities' , {origin:'pforum'});
$.when(request).then(func)
},
_getpforum:function(data){
var pforumCollectionView = new communityApp.CollectionViews.pforumCollectionViews({
collection: data
});
communityApp.activeTabView = pforumCollectionView;
// Populating the data
communityApp.activeTabLayout.pforum.show(pforumCollectionView);
},
});
});
view code is here
spine.module("communityApp", function (communityApp, App, Backbone, Marionette, $, _) {
// Load template
var a;
var pforumTemplateHtml = App.renderTemplate("pforumTemplate", {}, "communityModule/tabContainer/pforum");
// Define view(s)
communityApp.Views.pforumView = Marionette.ItemView.extend({
template: Handlebars.compile($(pforumTemplateHtml).html()),
tagName: "li",
onRender: function () {
this.object = this.model.toJSON();
},
events: {
"click #postcomment" : "alrt",
"click #recent-btn": "recent",
"click #my-posts": "myposts",
"click #popular-btn": "popular",
"click #follow-btn": "follow",
"click #my-posts": "LeftLinks",
"click #popular-btn": "LeftLinks",
"click #follow-btn": "LeftLinks"
},
postcomments : function ()
{
$("#recent-post-main-container").hide();
$("#recent-post-main-container2").show();
},
alrt : function ()
{
alert ("In Progress ......");
},
showCommentEiditor : function (){
$(".comment-popup-container").show();
$(".comment-txt-area").val('');
},
showPforumTab : function ()
{
$("#recent-post-main-container2").show();
$("#recent-post-main-container").hide();
},
showComments : function(){
$("#loading").show();
$(".tab-pane").hide();
$(".left-content").hide();
$("#recent-post-main-container2").show();
//$(".left-content-commentEditor").show();
$(".comm-tab-content-container").css('height','200px');
$(".comment-txt-area").val('');
$(".left-content-comment").show();
},
hideCommentPopup : function ()
{
$("#public-question-comment").hide();
},
// Show Loading sign
showLoading : function () {
$('#loading').show();
},
// UnLoading Function
hideLoading : function (){
$('#loading').hide();
},
// Add New Event Function
addEvent : function()
{
//$("#name").val(getBackResponse.user.FullName);
//$("#phone").val(getBackResponse.user.CellPhone);
//$("#email").val(getBackResponse.user.UserName);
$(".overly.addevent").show();
$('#lang').val(lat);
$('#long').val(long);
document.getElementById("my-gllpMap").style.width = "100%";
var my_gllpMap = document.getElementById("my-gllpMap");
google.maps.event.trigger( my_gllpMap, "resize" );
},
setValues : function(key,value)
{
window.localStorage.setItem(key,value);
},
getValues : function (key)
{
return window.localStorage.getItem(key);
},
closeAddEvent:function ()
{
$(".overly.addevent").hide();
},
// Show Over lay
showOverly:function ()
{
$('.overly-right-tab').show();
},
// Hide Loading sign
hideOverly : function()
{
$('.overly-right-tab').hide();
},
LeftLinks: function (e) {
var elem = $(e.target).closest('a');
var elem = $(e.target).closest('a');
var event = elem.attr('name');
switch (event) {
case "myposts":
var _this = $.extend({}, this, true);
_this.event = 'myposts';
this.LinkUrl.call(_this);
//$("#my-posts").addClass('active');
//$("#public-fourm-top-tab").addClass('TabbedPanelsTabSelected');
//$(".types").removeClass('active');
break;
case "recents":
var _this = $.extend({}, this, true);
_this.event = 'recents';
this.LinkUrl.call(_this);
$(".types").removeClass('active');
$("#recent-btn").addClass('active')
//$("#pforum").removeClass('active');
// $("#recent").addClass('active');
break;
case "populars":
var _this = $.extend({}, this, true);
_this.event = 'populars';
this.LinkUrl.call(_this);
$(".types").removeClass('active');
$("#popular-btn").addClass('active')
// $("#pforum").removeClass('active');
//$("#popular").addClass('active');
break;
case "follows":
var _this = $.extend({}, this, true);
_this.event = 'follows';
this.LinkUrl.call(_this);
$(".types").removeClass('active');
$("#follow-btn").addClass('active')
break;
}
},
LinkUrl: function (modalThis) {
communityApp.activeTabView.collection = []; // currently empty data
communityApp.activeTabView.render();
className: 'comm-main-container'
// uncomment these lines when getting data fro web service route, it will repopulate the data
var func = _.bind(function (data) {
communityApp.activeTabView.collection = data;
communityApp.activeTabView.render();
}, this);
switch (this.event) {
case "myposts":
$.when(App.request('alertLinks:entities', {
origin: 'pforum',
event: this.event
})).then(func);
break;
case "recents":
$.when(App.request('alertLinks:entities', {
origin: 'pforum',
event: this.event
})).then(func);
break;
case "populars":
$.when(App.request('alertLinks:entities', {
origin: 'pforum',
origin1:'popular',
event: this.event
})).then(func);
break;
case "follows":
$.when(App.request('alertLinks:entities', {
origin: 'pforum',
event: this.event
})).then(func);
break;
}
return true;
}
});
// define collection views to hold many communityAppView:
communityApp.CollectionViews.pforumCollectionViews = Marionette.CollectionView.extend({
tagName: "ul",
itemView: communityApp.Views.pforumView
});
});
Whenever I need to share an event between a view and controller I usually wire up the listeners within the module that instantiates the controller. This example is a bit contrived, but it gets the point across. The full working code is in this codepen. The relevant bit is copied here. Notice the line this.listenTo(view, 'itemview:selected', this.itemSelected); where the view's event triggers a method on the controller.
App.module("SampleModule", function(Mod, App, Backbone, Marionette, $, _) {
// Define a controller to run this module
// --------------------------------------
var Controller = Marionette.Controller.extend({
initialize: function(options){
this.region = options.region
},
itemSelected: function (view) {
var logView = new LogView();
$('#log').append(logView.render('selected:' + view.cid).el);
},
show: function(){
var collection = new Backbone.Collection(window.testData);
var view = new CollectionView({
collection: collection
});
this.listenTo(view, 'itemview:selected', this.itemSelected);
this.region.show(view);
}
});
// Initialize this module when the app starts
// ------------------------------------------
Mod.addInitializer(function(){
Mod.controller = new Controller({
region: App.mainRegion
});
Mod.controller.show();
});
});
The other way to accomplish this, if you cannot wire it all up within the same module, is to use Marionette's messaging infrastructure. For example, you can use the application's event aggregator to pass events around.

Cannot set property 'new_form' of undefined

I'm having trouble with a Backbone.js tutorial from Treehouse. Here's my code:
var NotesApp = (function () {
var App = {
stores: {}
}
App.stores.notes = new Store('notes');
// Note Model
var Note = Backbone.Model.extend({
//Local Storage
localStorage: App.stores.notes,
initialize: function () {
if (!this.get('title')) {
this.set({
title: "Note at " + Date()
})
};
if (!this.get('body')) {
this.set({
body: "No Body"
})
};
}
})
//Views
var NewFormView = Backbone.View.extend({
events: {
"submit form": "createNote"
},
createNote: function (e) {
var attrs = this.getAttributes(),
note = new Note();
note.set(attrs);
note.save();
},
getAttributes: function () {
return {
title: this.$('form [name=title]').val(),
body: this.$('form [name=body]').val()
}
}
});
window.Note = Note;
$(document).ready(function () {
App.views.new_form = new NewFormView({
el: $('#new')
});
})
return App
})();
And I get the error: Cannot set property 'new_form' of undefined
I've tried to go back and copy the code as close as possible, but I still couldn't get it to work. Any suggestions?
After stores: {} add ,
views: {}.
You need an object to attach your view to - JavaScript has no vivification

Backbone routing

I am creating an app that will list the days of an event as buttons, then let you add dates and click each date to get a new "daily calendar".
This is my first real world app using backbone and underscore, so I keep running into road blocks. I would really appreciate anyone helping me out.
I am now at the point where my collection is full of dates, and I can add to those dates. Now what I am trying to figure out it routing the links to switch out the calendar, depending on the selected date.
Heres what I have relating to this part of the app so far:
Collections
var Days = Backbone.Collection.extend({
url: daysURL
});
var Calendar = Backbone.Collection.extend({
url: URL
});
Models
var Header = Backbone.Model.extend();
var header = new Header();
var ConferenceDay = Backbone.Model.extend();
var conferenceDay = new ConferenceDay();
View
var HeaderView = Backbone.View.extend({
el: $(".conf_days"),
template: _.template($('#days').html()),
events: {
'click a.day-link': 'changeDay',
'click #add_day' : 'addDay',
'click #previous_day' : 'prevDay',
'click #next_day' : 'nextDay',
'click #delete_day' : 'deleteDay'
},
initialize: function(){
_.bindAll(this, "render");
this.collection = new Days();
this.collection.fetch();
this.collection.bind("reset", this.render, this);
},
render: function(){
var JSONdata = this.collection.toJSON();
this.$el.html(this.template({days: JSONdata}));
console.log(JSON.stringify(JSONdata))
return this;
},
changeDay: function(e){
AppRouter.history.navigate($(this).attr('href'));
return false;
},
addDay: function() {
newDate = Date.parse($('.day-link:first-child').text()).add(1).day();
var newDay = new ConferenceDay();
newDay.set({date_formatted: newDate});
this.collection.add(newDay)
newDay.save({
success: function(){
alert('yes')
},
error: function(){
alert('no')
}
});
},
deleteDay: function(event){
var id = $('.day-link:last-child').data("id");
$('.day-link:last-child').remove();
},
prevDay: function() {
},
nextDay: function() {
},
loadTimes: function(){
var html = time.get('times');
$('.time_td').append(html);
}
});
var headerView = new HeaderView({ model: header });
ConferenceView = Backbone.View.extend({
el: $(".calendar"),
template: _.template($('#calendar').html()),
events: {
},
initialize: function(){
//this.listTracks();
this.collection = new Calendar();
this.collection.fetch();
this.collection.bind("reset", this.render, this);
},
render: function(){
var JSONdata = this.collection.toJSON();
this.$el.html(this.template({days: JSONdata}));
},
listTracks: function() {
}
});
var conferenceView = new ConferenceView({model:conferenceDay});
My current routing
var AppRouter = Backbone.Router.extend({
routes: {
'' : 'index',
'day/:id' : 'changeDay'
},
initialize: function() {
},
index: function() {
},
changeDay: function(id){
alert("changed");
this.calender.changeDay(id);
this.dayView = new ConferenceView({model:conferenceDay});
$('#calender').html(this.dayView.render().el).text('test');
},
});
var app = {
init: function() {
var routes = new AppRouter();
Backbone.history.start({pushState: true});
}
}
app.init();
Ideally, I would like the user to click the day-link button and have the url update via push state to the day/:id and then the #calender template would update with the correct model info received from the day update.
There's a lot of code in your post, so I'm not 100% sure the below will cover everything you need to do, but it's a start
This event handler might be causing some problems:
changeDay: function(e){
AppRouter.history.navigate($(this).attr('href'));
return false;
}
On a detail level, couple of things are off here:
You don't need to reference history. I'm not sure that the router even has such property. You should call AppRouter.navigate instead.
If you want the router to trigger your changeDay route method, you need to pass an option trigger:true, like so:
AppRouter.navigate($(this).attr('href'), {trigger:true}).
However, the actual solution is still simpler than that. You can remove the HeaderView.changeDay event handler, and the click a.day-link event binding from the events hash entirely. Backbone Router will detect the changed URL, and call the router method which matches the new URL automatically.

Categories

Resources