I'm beginning a large scale javascript application with Marionette. A Marionette application has a concept of application Modules and RequireJS is also used to break code into modules,
currently I have this for the start of my application:
require([ "jquery", "underscore", "backbone", "marionette" ],
function ($, _, Backbone, Marionette) {
$(function() {
App = new Marionette.Application();
App.addInitializer(function(options) {
App.addRegions({
mainArea: "#mainArea"
});
});
App.on("start", function() {
// done starting up, do stuff here
});
App.start();
});
});
If I wanted to add a view would I do something like the following in a file?
require([ "jquery", "underscore", "backbone", "marionette" ],
function($, _, Backbone, Marionette) {
App.module("FirstView", function(FirstView, App, Backbone, Marionette, $, _) {
return Marionette.ItemView.extend({
//define view stuff in here
});
});
});
I'm not sure how I'd get this code to actually run, any help is much appreciated
Marionette's modules are meant to be a simple alternative to RequireJS (and other) module formats. I would not recommend using them together, as noted in the wiki:
https://github.com/marionettejs/backbone.marionette/wiki/AMD-Modules-vs-Marionette's-Modules
IMHO I like to differ from the view point stated above "Marionette's modules are meant to be a simple alternative to RequireJS (and other) module formats."
I like to draw a comparison between Require.js modules and Marionette.js modules with C#'s assembly and namespace concepts. Marionette.js's modules help us group definitions of various building blocks based on functionality, while Require.js could be used to load / inject dependencies.
Again, this is my view / understanding (based on discussions with David Sulc on his book 'Structuring Backbone Code with RequireJS and Marionette Modules'), which has helped in my implementation. In a way we can use Marionette.js and Require.js together as described below.
The example below is a small Library Manager app (sample) which could be found online # https://github.com/srihari-sridharan/LibraryManagement. The code below (omitting insignificant bits and pieces) creates the application object and renders the list of books after initialization. Please find it here - https://github.com/srihari-sridharan/LibraryManagement/blob/master/app/js/app.js
define([
'marionette',
'modules/config/marionette/regions/dialog'], function (Marionette) {
// Create the application object
var LibraryManager = new Marionette.Application();
// Add regions to the application object
LibraryManager.addRegions({
//Header
headerRegion: "#header-region",
//Main
mainRegion: "#main-region",
//Footer
footerRegion: "footer-region",
//Overlay Dialog
dialogRegion: Marionette.Region.Dialog.extend({
el:"#dialog-region"
})
});
// Subscribe to Initialize After event.
LibraryManager.on('initialize:after', function() {
if(Backbone.history){
require(['modules/books/booksModule', 'modules/about/aboutModule'], function (){
Backbone.history.start();
if(LibraryManager.getCurrentRoute() === ''){
LibraryManager.trigger("books:list");
}
});
}
});
// Return the application object.
return LibraryManager;
});
Next we define the module / sub-modules based on the functionality. This will also have a module specific router and will wire controllers and handle routes. Note the require call to controllers. This code is present in https://github.com/srihari-sridharan/LibraryManagement/blob/master/app/js/modules/books/booksModule.js
define(['app'], function (LibraryManager) {
// Define a new module for Books - BooksModule
LibraryManager.module('BooksModule', function (BooksModule, LibraryManager, Backbone, Marionette, $, _) {
BooksModule.startWithParent = false;
BooksModule.onStart = function () {
console.log('Starting BooksModule.');
};
BooksModule.onStop = function () {
console.log('Stopping BooksModule.');
};
});
// Define a new module for a Router specific to BooksModule
LibraryManager.module('Routers.BooksModule', function (BooksModuleRouter, LibraryManager, Backbone, Marionette, $, _) {
BooksModuleRouter.Router = Marionette.AppRouter.extend({
appRoutes: {
'books': 'listBooks',
'books(?filter:=criterion)': 'listBooks',
'books/:id': 'showBook',
'books/:id/edit': 'editBook'
}
});
var executeAction = function (action, arg) {
LibraryManager.startSubModule('BooksModule');
action(arg);
LibraryManager.execute('set:active:header', 'books');
};
var API = {
// This is where we are using / referring to our controller
listBooks: function (criterion) {
require(['modules/books/list/listController'], function (ListController) {
executeAction(ListController.listBooks, criterion);
});
},
showBook: function (id) {
require(['modules/books/show/showController'], function (ShowController){
executeAction(ShowController.showBook, id);
});
},
editBook: function (id) {
require(['modules/books/edit/editController'], function (EditController) {
executeAction(EditController.editBook, id);
});
}
};
// Navigating routes.
LibraryManager.on('books:list', function () {
LibraryManager.navigate('books');
API.listBooks();
});
LibraryManager.on('books:filter', function(criterion) {
if(criterion){
LibraryManager.navigate('books?filter=' + criterion);
}
else{
LibraryManager.navigate('books');
}
});
LibraryManager.on('book:show', function (id) {
LibraryManager.navigate('books/' + id);
API.showBook(id);
});
LibraryManager.on("book:edit", function(id){
LibraryManager.navigate('books/' + id + '/edit');
API.editBook(id);
});
LibraryManager.addInitializer(function () {
new BooksModuleRouter.Router({
controller: API
});
});
});
return LibraryManager.BooksModuleRouter;
});
Finally we have the definitions for our views, models and controllers. These definitions will be tied to module / sub module objects.
The view code is shown below. Look at the .extend() methods. They are assigned to variables attached to the BooksModule.List.View sub module. https://github.com/srihari-sridharan/LibraryManagement/blob/master/app/js/modules/books/list/listView.js
define(['app',
'tpl!modules/books/list/templates/layout.html',
'tpl!modules/books/list/templates/panel.html',
'tpl!modules/books/list/templates/none.html',
'tpl!modules/books/list/templates/list.html',
'tpl!modules/books/list/templates/listItem.html'],
function (LibraryManager, layoutTemplate, panelTemplate, noneTemplate, listTemplate, listItemTemplate) {
LibraryManager.module('BooksModule.List.View', function(View, LibraryManager, Backbone, Marionette, $, _) {
View.Layout = Marionette.Layout.extend({
template: layoutTemplate,
regions:{
panelRegion: '#panel-region',
booksRegion: '#books-region'
}
});
View.Panel = Marionette.ItemView.extend({
// More code here!
});
View.Book = Marionette.ItemView.extend({
// More code here!
});
var NoBooksView = Marionette.ItemView.extend({
template: noneTemplate,
tagName: "tr",
className: "alert"
});
View.Books = Marionette.CompositeView.extend({
// More code here!
});
});
return LibraryManager.BooksModule.List.View; // Return the definition.
});
The controller code is shown below. This gets called from the code in booksModule.js. The controller definition is attached to BooksModule.List sub module.
define(['app', 'modules/books/list/listView'], function (LibraryManager, View) {
LibraryManager.module('BooksModule.List', function (List, LibraryManager, Backbone, Marionette, $, _) {
List.Controller = {
listBooks: function (criterion) {
require(['common/views', 'entities/book'], function (CommonViews) {
var loadingView = new CommonViews.Loading();
LibraryManager.mainRegion.show(loadingView);
var fetchingBooks = LibraryManager.request('book:entities');
var booksListLayout = new View.Layout();
var booksListPanel = new View.Panel();
require(['entities/common'], function (FilteredCollection) {
$.when(fetchingBooks).done(function (books) {
// More code here!
});
if(criterion){
filteredBooks.filter(criterion);
booksListPanel.once('show', function () {
booksListPanel.triggerMethod("set:filter:criterion", criterion);
});
}
var booksListView = new View.Books({
collection: filteredBooks
});
booksListPanel.on('books:filter', function (filterCriterion) {
filteredBooks.filter(filterCriterion);
LibraryManager.trigger("books:filter", filterCriterion);
});
booksListLayout.on("show", function(){
booksListLayout.panelRegion.show(booksListPanel);
booksListLayout.booksRegion.show(booksListView);
});
booksListPanel.on('book:new', function () {
require(["modules/books/new/newView"], function (NewView) {
// More code here!
});
LibraryManager.dialogRegion.show(view);
});
});
booksListView.on('itemview:book:show', function (childView, model) {
LibraryManager.trigger("book:show", model.get('id'));
});
booksListView.on('itemview:book:edit', function(childView, model) {
require(['modules/books/edit/editView'], function (EditView) {
// More code here!
LibraryManager.dialogRegion.show(view);
});
});
booksListView.on("itemview:book:delete", function (childView, model) {
model.destroy();
});
LibraryManager.mainRegion.show(booksListLayout);
});
});
});
}
}
});
return LibraryManager.BooksModule.List.Controller; // Return the definition.
});
Thus require.js modules and marionette modules can coexist. The following are the advantages.
Much cleaner organization of source code and clearer separation of concerns.
Module start and stop methods provide provision to initialize and cleanup objects.
When you model functionalities and sub-functionalities as modules and sub modules, we have more granular control over what resides in memory and what should not.
Also, module definition can be split across multiple files.
Please post your thoughts. Thanks for reading.
PS: Based on the above view point, please find the changes to your example below:
require([ "jquery", "underscore", "backbone", "marionette" ],
function($, _, Backbone, Marionette) {
App.module("FirstView", function(FirstView, App, Backbone, Marionette, $, _) {
FirstView.View = Marionette.ItemView.extend({
//define view stuff in here
});
return FirstView.View;
});
});
Related
I have a backbone app that uses require.js.
Prior to using require my Backbone router looked something like this.
APP.views = {};
APP.Router = Backbone.Router.extend({
routes: {
'(/)' : 'index',
'about(/)' : 'about'
},
initialize : function(){
Backbone.history.start({ pushState: true });
},
index: function() {
this.showView( new APP.Views.IndexView() );
},
about: function() {
this.showView( new APP.Views.AboutView() );
},
showView : function( view ) {
if ( APP.views.current ) {
APP.views.current.remove();
}
APP.views.current = view;
$( '#page' ).html( view.render().$el );
}
});
I would stash the 'current' view in a global variable and kill the existing view each time a route was changed and life was good.
But, how do I achieve this with require.js ?
My requirejs router currently looks like the following but I'm not sure how to remove the existing views. Although, I have not noticed any of the typical "zombie view" symptoms I feel like I should be removing the existing views.
define( function( require ){
// DEPS
var $ = require('jquery'),
_ = require('underscore'),
Backbone = require('backbone');
// ROUTER
var Router = Backbone.Router.extend({
routes: {
'(/)' : 'index',
'about(/)' : 'about'
},
initialize : function(){
Backbone.history.start({ pushState: true });
},
index: function(){
this.showPage('index');
},
about: function() {
this.showPage('about');
},
showPage : function( pageName ) {
var view = 'views/pages/' + pageName;
require( [ view ] , function( Page ) {
var page = new Page();
$('#page').html( page.render().el );
});
}
});
return Router ;
});
Even before using require.js, a global wasn't needed.
Just put the current view into a router property.
initialize : function() {
this.$page = $('#page');
Backbone.history.start({ pushState: true });
},
showView : function(view) {
if (this.current) this.current.remove();
this.$page.html((this.current = view).render().el);
}
Then, same thing applies to your async require case:
showPage : function(pageName) {
if (this.current) this.current.remove();
var view = 'views/pages/' + pageName,
self = this;
require([view], function(Page) {
self.$page.html((self.current = new Page()).render().el);
});
}
But even then, I don't feel like requiring each view with an async require is worth it. You're just slowing down your application with a lot of extra requests.
Just define the dependencies for each module.
define([
'jquery',
'backbone',
'views/index',
'views/about'
], function($, Backbone, IndexView, AboutView){
// ...
});
While in development, you'll see a lot of request each time you refresh, but when ready for production, build a minified bundle of all the js files with require optimizer.
Also note that you can have module scope global, which are just local variable declared at the root of a module scope (IIFE or with require.js).
(function() {
var currentView;
var Router = Backbone.Router.extend({
// ...snip...
showView: function(view) {
if (currentView) currentView.remove();
this.$page.html((currentView = view).render().el);
}
});
})();
I have many views which controllers alsmost have the same functions. What I want is to have a mother controller or class or whatever, which have all this function abstract or with implementation. The view controller will then inherit or extend this mother controller. I want to be sure that even if I dont explicitly implement the function in the view controller the following code will still work.
content.onMove(); // Content is the controller of the view
and I will not get this kind of error "could not find onMove()"
I dont have any start point
Thank you.
SAPUI5 use require.js principles :
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function (Controller) {
"use strict";
return Controller.extend("", {
});
});
So you can have a look to the require.js documentation to know more about class structuration.
I think you will can't have asbract because it do not exist in JS but you can overwrite very easily the function.
For example you will have a base controller like that :
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function (Controller) {
"use strict";
return Controller.extend("sap.mydemo.baseController", {
onShowHello : function () {
alert("Hello World");
},
onShowGoodBye : function () {
alert("Goodbye World");
}
});
});
and just call it on your own controller :
ap.ui.define([
"sap/mydemo/baseController"
], function (Controller) {
"use strict";
return Controller.extend("", {
SayHelloAndGoodBye: function(){
Controller.SayHello();
Controller.SayGoodBye();
}
});
});
This should work.
I just started to lean Backbone, and underscore template, not sure if the structure suitable for it.
The question is, when I reload a template, how to re-bind event from Backbone which is re-run the events function.
The example is simply load an index page, insert main_option template into the page, and jump between main_option, and role_view template.
Here is the app.js which I put router in there:
define(['jquery', 'underscore', 'backbone', 'views/role_view', 'views/main_options'], function ($, _, Backbone, rolePage, mainOptions) {
var appRouter = Backbone.Router.extend({
$el: $('.container'),
initialize: function () {
this.mainOptionPage = mainOptions;
this.loginView = rolePage;
},
routes: {
"": "mainOption",
"views/role_view": "login"
},
mainOption: function () {
this.$el.html(this.mainOptionPage.render().$el);
},
login: function () {
this.$el.html(this.loginView.render().$el);
}
});
var router = new appRouter();
Backbone.history.start();
});
Here is the main_option.js
define(['jquery', 'underscore', 'backbone'], function($, _, Backbone){
var Person = Backbone.Model.extend({
defaults: {
name: 'Guest Worker',
age: 23,
occupation: 'worker'
}
});
var testView = Backbone.View.extend({
$el: $('#indexPage'),
initialize: function () {
var self = this;
$.get('/test/templates/mainOptions.html').success(function (data) {
self.template_loaded(data);
template = _.template(data, {name: "Test"});
}, 'html');
},
events: {
'click .signButton': 'pageToSign'
},
pageToSign: function (e) {
e.preventDefault();
Backbone.history.navigate("views/role_view", {trigger: true});
},
template_loaded: function (html) {
var template = _.template(html, {name: "Test"});
this.$el.html(template);
return this;
}
});
var person = new Person;
return new testView({model: person});
});
and final page is role_view.js
define(['jquery', 'underscore', 'backbone'], function($, _, Backbone){
var role = Backbone.View.extend({
initialize: function(){
var self = this;
$.get('/test/templates/chooseRole.html').success(function(html){
self.template_loaded(html);
});
},
events: {
'click .parentButton': 'parentClick'
},
template_loaded: function(html) {
var template = _.template(html, {name: "Test"});
this.$el.html(template);
return this;
},
parentClick: function(e) {
e.preventDefault();
Backbone.history.navigate("", {trigger: true});
}
});
return new role();
});
Thanks.
You real problem is that you're reusing views rather than destroying and creating them as needed. In your router, you have this:
mainOption: function () {
this.$el.html(this.mainOptionPage.render().$el);
},
login: function () {
this.$el.html(this.loginView.render().$el);
}
You call this.$el.html the first time, the view goes up, and everything seems to be okay. Then you switch views by calling this.$el.html and everything still seems to be okay. But the next time you switch views, your events are gone. This happens because of the way jQuery's html function works; from the fine manual:
When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.
Emphasis mine. Calling this.$el.html will destroy the event bindings on the previous content (such as this.mainOptionsPage.el or this.loginView.el).
If you create and destroy views as needed:
define(['jquery', 'underscore', 'backbone'], function($, _, Backbone){
// Your Person model goes in its own file or possibly in the router file for now...
var TestView = Backbone.View.extend({
//...
});
return TestView; // Return the view "class", not an instance.
});
define(['jquery', 'underscore', 'backbone'], function($, _, Backbone){
var Role = Backbone.View.extend({
//...
});
return Role;
});
define(['jquery', 'underscore', 'backbone', 'views/role_view', 'views/main_options', 'models/person'], function ($, _, Backbone, Role, TestView, Person) {
var person = new Person; // The person model is managed here.
var appRouter = Backbone.Router.extend({
//...
initialize: function () {
// Don't need anything in here anymore.
},
//...
mainOption: function () {
// Create a new view when we need it.
this.switchTo(new TestView({ model: person }));
},
login: function() {
// Create a new view when we need it.
this.switchTo(new Role);
},
switchTo: function(view) {
// Destroy the old view since we don't need it anymore.
if(this.currentView)
this.currentView.remove();
// Keep track of the new current view so that we can
// kill it alter and avoid leaks.
this.currentView = view;
this.$el.html(this.currentView.render().el);
}
});
//...
});
I'm having troubles handling events between my views and collections. In the below example you can find a short version of what does my webapp look like and how are the events being handled now.
What happens here is that when switching from menu1 to menu2 or even when going backwards, it causes that the "APP:change_city" event listener is stacked up. So when I then trigger this event , it calls the method OnCityChange() as many times as I switched between the menus.
I'm now not really sure whether I'm using the event aggregator (eMgr) correctly.
Can anyone please assist?
eMgr.js
define(['backbone.wreqr'],function(Wreqr){
"use strict";
return new Wreqr.EventAggregator();
})
AppRouter.js
define(['marionette'], function (Marionette) {
"use strict";
var AppRouter = Marionette.AppRouter.extend({
appRoutes: {
'menu1' : 'showMenu1',
'menu1' : 'showMenu2'
}
});
return AppRouter;
});
AppControler.js
define(['underscore', 'backbone', 'marionette', '../eMgr'], function (_, Backbone, Marionette, eMgr) {
"use strict";
var Controller = Marionette.Controller.extend({
initialize: function(){
console.log("AppRouter - Init")
},
showMenu1: function (city) {
console.log(" [Info] [AppControler] opening Menu1");
eMgr.trigger("APP:open_menu", { menu: "Menu1", city: city});
},
showMenu2: function (city) {
console.log(" [Info] [AppControler] opening Menu2");
eMgr.trigger("APP:open_menu", { menu: "Menu2", city: city});
}
});
return Controller;
});
App.js
define([ 'backbone', 'underscore', 'marionette', 'eMgr',
'layouts/MainMenu/layoutview.menu1',
'layouts/MainMenu/layoutview.menu2',
'controllers/AppController', 'routers/AppRouter'],
function (Backbone, _, Marionette, eMgr,
lv_mainmenu1, lv_mainmenu2,
AppController, AppRouter) {
"use strict";
var MyApp = new Marionette.Application();
var controller = new AppController();
MyApp.addRegions({
.....
mainmenu: '#main_menu',
.....
});
MyApp.listenTo(eMgr, "menu_changed",function(eData){
switch(eData.menu){
case "Menu1":
MyApp.mainmenu.show(new lv_mainmenu1(eData));
break;
case "Menu2":
MyApp.mainmenu.show(new lv_mainmenu2(eData));
break;
}
});
MyApp.addInitializer(function(options) {
var router = new AppRouter({
controller : controller
});
});
MyApp.on("start", function(){
if (Backbone.history){
Backbone.history.start();
}
});
$(document).ready(function() {
MyApp.start();
});
});
layoutview.menu1.js
define([ 'backbone', 'underscore', 'marionette',
'templates/template.mainmenu',
'layouts/MainMenu/collectionview.categories'],
function (Backbone, _, Marionette, t_Menus, c_Categories, cv_Categories) {
"use strict";
var Menu1LayoutView = Marionette.LayoutView.extend({
template: t_Menus['menu1'],
regions: {
menu : '#menu'
},
initialize: function(options){
this.city = options.city
},
onRender: function(){
},
onShow: function(){
this.menu.show(new cv_Categories({city:this.city}));
}
});
return Menu1LayoutView;
});
collectionview.categories.js
define([ 'backbone', 'underscore', 'marionette',
'layouts/MainMenu/compositeview.subcategories',
'collections/MainMenu/MM.collection.categories'],
function (Backbone, _, Marionette, cv_Subcategories, c_Categories) {
"use strict";
var CategoriesCollectionView = Marionette.CollectionView.extend({
initialize: function(options){
this.collection = new c_Categories([], {city: options.city});
},
getChildView: function(model){
return cv_Subcategories;
},
onRender: function(){
},
onShow: function(){
}
});
return CategoriesCollectionView;
});
This is where all the categorie's data are fetched from , it also re-fetches the data once the APP:change_city event is being triggered.
MM.collection.categories.js
define([ 'underscore', 'backbone', 'eMgr','models/MainMenu/MM.model.category'], function(_, Backbone, eMgr, m_Category){
var CategoriesCollection = Backbone.Collection.extend({
model: m_Category,
initialize: function(attr, opts) {
this.city = opts.city;
this.fetch();
eMgr.once("APP:change_city", this.OnCityChange, this)
},
url: function(){
return 'AF_GetCategories?city='+this.city;
},
OnCityChange: function(eData){
/// this is the part which is being called multiple times !!!!! ////
/// when checking eMgr's events , it shows that the events are stacking up ..
this.url= 'AF_GetCategories?city='+eData.city;
this.fetch();
}
});
return CategoriesCollection;
});
compositeview.subcategories.js
define([ 'backbone', 'underscore', 'marionette',
'templates/template.mainmenu',
'layouts/MainMenu/itemview.subcategory'],
function (Backbone, _, Marionette, t_MainMenu, iv_Subcategory) {
"use strict";
var SubcategoriesCompositeView = Marionette.CompositeView.extend({
template: t_Menus['subcategorieslayout'],
childViewContainer: "#category-wrapper",
getChildView: function(model){
return iv_Subcategory;
},
initialize: function(){
this.collection = this.model.get("subcategories");
},
onRender: function(){
},
onShow: function(){
this.$el.find("#loading").fadeOut(150);
}
});
return SubcategoriesCompositeView;
});
I have come to a conclusion that keeping the event listeners this.listenTo("custom_event", this.do_something) in either model or collection isn't a good idea. The events weren't cleaned up properly while switching between menu1 and menu2. It only worked when I manually called eMgr.stopListening() before loading any views.
So I tried moving all the event listeners from models/collections to their views and Voila!...it all worked! Events are no longer being triggered multiple times as before.
I am using requireJS in combination with backbone:
define([
"jquery",
"underscore",
"backbone",
"models/modelA"
], function( $, _, Backbone, MyModel ) {
var viewA = Backbone.View.extend({
initialize: function() {
this.model = new MyModel();
}
});
return viewA;
});
I want to create a new View module, ViewB, that has all of the same methods as viewA, but that uses a different model in place of modelA. I know I can override the initialize function, but I am wondering if there is a more concise way, to avoid duplication of code...
define([
"jquery",
"underscore",
"backbone",
"views/viewA",
"models/modelB"
], function( $, _, Backbone, ViewA, myModel ) {
var viewB = ViewA.extend({
initialize: function() {
this.model = new MyModel();
}
});
return viewB;
});
If the two views are exactly the same, just pass in the instantiated model instead of creating it in initialize. Then you only need to define one view.
define([
"jquery",
"underscore",
"backbone"
// no model module needed here.
], function( $, _, Backbone ) {
var viewA = Backbone.View.extend({
initialize: function() {
}
});
return viewA;
});
Then in some other module which requires both models and the view:
var modelA = new ModelA();
var modelB = new ModelB();
// create 2 instances of ViewA with different model passed in
var viewA = new ViewA({model: modelA});
var viewB = new ViewA({model: modelB});
When created like this, each view will have this.model set to the instance you pass in.
define(['views/ViewA'], function() {
var ViewA = require('views/ViewA'), // require ViewA
ViewB = ViewA.extend({
// add all your ViewB specific methods/properties here
});
return ViewB; // return ViewB from the RequireJS module so it can be used elsewhere
});