How to include moment.js inside marionette application? - backbone.js

I am a newbie to Marionette and moment.js and as such to javascript and web programming, hence please excuse me if my question sounds stupid.
Here is what I want to achieve.
I want to use moment.js globally in my marionette application, and hence I want to do something like this, but how can I do it?
SuperAppManager.module('AppointmentsApp.List', function (List, SuperAppManager, Backbone, Marionette, $, _, moment) {
var date = moment();
}
Regards,
Chidan

Try this, according to Custom Arguments from Marionette documentation:
SuperAppManager.module('AppointmentsApp.List', function (List, SuperAppManager, Backbone, Marionette, $, _, moment) {
var date = moment();
}, moment);

Related

Define global variable with Typescript Angularjs in components

My application uses components and boostrapper. I want to create a datepicker which will set a global date variable. I have tried to create a service, use the rootscope and basically all the solutions I could find on stackoverflow but it doesn't seem to work.
What would be the correct approach to create a global variable shared across all components?
It's generally not a great idea to use a global variable to store state like this, as it's hard to track what is mutating it.
Assuming Angular 1.x, to share information like this, you can simply create a service which stores whatever data you are tracking. I'll add the disclaimer here that state management in web apps is still a tricky problem. You could go for a Redux styled approach, but I'll keep it basic for now.
angular
.module('app', [])
.controller('testController', function(testService) {
console.log(testService.getDate());
});
angular.module('app')
.service('testService', function() {
var date = new Date();
function getDate() {
return date;
}
function setDate(newDate) {
date = newDate;
}
});
This way, you have an interface to read/mutate the date. You can inject it into as many controllers/components as you like.
Hope that helps (I'm aware the answer isn't in Typescript, but I assume since the problem has a basic solution, it doesn't matter too much - if you want a Typescript answer, let me know and I'll change it for you :) ).

Issue with this.$el.find in Backbone framework

I get am "TypeError: this.$el is undefined" in my backbone View.
Here is my simple backbone view code
var tableViews = Backbone.View.extend({
initialize: function() {
console.log("initialized");
},
render: function() {
this.$el.find(".clgcrt").removeClass("hidden");
}
});
I included "http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js" url for my backbone.
Is there any problem with above backbone version?
You're using a very, very old version of Backbone. this.$el didn't get introduced until version 0.9.0.
You'll, at a minimum, need to use this version: http://ajax.cdnjs.com/ajax/libs/backbone.js/0.9.0/backbone-min.js.
Also, Justin in the comments mentioned you'll also need to use a recent version of Underscore.js, http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js. This needs to be included before you include Backbone.

Best practice for shared objects in Backbone/Require Application

I've been developing Backbone applications for a little while now, and am just starting to learn to use Backbone with Require.js.
In my backbone app that I am refactoring, I defined a namespace like this: App.model.repo. This model is used over and over again in different views. I do the same thing with a few collections, for example, App.collection.files. These models and collections are bootstrapped in with the initial index file request.
I did find this example, which looks like a great way to get that bootstrapped data in. However, I am struggling with the best way to reuse/share these models and collection between views.
I can think of three possible solutions. Which is best and why? Or is there another solution I am missing entirely?
Solution 1
Define these common modules and collections in the index (when they are bootstrapped in), and then pass them along to each Backbone view as an option (of initialize).
define(['jquery', 'underscore', 'backbone', 'handlebars', 'text!templates/NavBar.html'],
function($, _, Backbone, Handlebars, template){
return Backbone.View.extend({
template: Handlebars.compile(template),
initialize: function(options){
this.repoModel = options.repoModel; // common model passed in
}
});
}
);
These seems clean as far as separation, but could get funky quick, with tons of things being passed all over the place.
Solution 2
Define a globals module, and add commonly used models and collections to it.
// models/Repo.js
define(['backbone'],
function(Backbone){
return Backbone.Model.extend({
idAttribute: 'repo_id'
});
}
);
// globals.js (within index.php, for bootstrapping data)
define(['underscore', 'models/Repo'],
function(_, RepoModel){
var globals = {};
globals.repoModel = new Repo(<?php echo json_encode($repo); ?>);
return globals
}
);
define(['jquery', 'underscore', 'backbone', 'handlebars', 'text!templates/NavBar.html', 'globals'],
function($, _, Backbone, Handlebars, template, globals){
var repoModel = globals.repoModel; // repoModel from globals
return Backbone.View.extend({
template: Handlebars.compile(template),
initialize: function(options){
}
});
}
);
Does this solution defeat the whole point of AMD?
Solution 3
Make some models and collections return an instance, instead of a constructor (effectively making them Singletons).
// models/repo.js
define(['backbone'],
function(Backbone){
// return instance
return new Backbone.Model.extend({
idAttribute: 'repo_id'
});
}
);
// Included in index.php for bootstrapping data
require(['jquery', 'backbone', 'models/repo', 'routers/Application'],
function($, Backbone, repoModel, ApplicationRouter){
repoModel.set(<?php echo json_encode($repo); ?>);
new ApplicationRouter({el: $('.site-container')});
Backbone.history.start();
}
);
define(['jquery', 'underscore', 'backbone', 'handlebars', 'text!templates/NavBar.html', 'models/repo'],
function($, _, Backbone, Handlebars, template, repoModel){
// repoModel has values set by index.php
return Backbone.View.extend({
template: Handlebars.compile(template),
initialize: function(options){
}
});
}
);
This I worry could get real confusing about what is a constructor and what is an instance.
End
If you read this far, you are awesome! Thanks for taking the time.
In my case, I prefer option 3. Although, to prevent confusion, I put every singleton instance in their own folder named instances. Also, I tend to separate the model/collection from the instance module.
Then, I just call them in:
define([
"instance/photos"
], function( photos ) { /* do stuff */ });
I prefer this option as every module is forced to define its dependencies (which is not the case via namespace for example). The solution 2 could do the job, but if I'm using AMD, I want my module as small as possible - plus keeping them small make it easier to unit test.
And lastly, about unit test, I can just re-define the instance inside my unit test to use mock data. So, definitely, option 3.
You can see an example of this pattern on an Open source app I'm working on ATM: https://github.com/iplanwebsites/newtab-bookmarks/tree/master/app
I would take a look at this example repo https://github.com/tbranyen/github-viewer
It is a working example of backbone boiler plate (https://github.com/tbranyen/backbone-boilerplate)
Backbone Boiler plate does a lot of unnecessary fluff, but what is really useful about it, is that it gives some clear directions on common patterns for developing complex javascript apps.
I'll try and come back later today to answer you question more specifically (if someone doesn't beat me to it :)
I prefer Solution 1. It is generally good to avoid using singletons, and using globals is also something to avoid, especially since you are using RequireJS.
Here are some advantages I can think of for Solution 1:
It makes the view code more readable. Someone looking at the module for the first time can immediately see from looking at the initialize function which models it uses. If you use globals, something might be accessed 500 lines down in the file.
It makes it easier to write unit tests for the view code. Since you could possibly pass in fake models in your tests.

Backbone structure

I'm new to backbone, but have watched several tutorial screencasts on it, both with and without requirejs.
My question involves the setup structure (both file structure if using require, and/or variable/object structure).
Most of the tutorials I have watched, seem to prefer a App.Models, App.Collections, and App.Views approach, and each item inside has the name of the module: ie,
App.Models.todo = Backbone.Model.extend({...});
App.Collections.todos = Backbone.Collection.extend({...});
App.Views.todo = Backbone.View.extend({...});
After a little research, trying to find someone that uses the same style as I would like to use, I finally found: File structure for a web app using requirejs and backbone. They seem to prefer more of a App.[Module Name] method: ie,
App.Todo.Model = Backbone.Model.extend({...});
App.Todo.Collection = Backbone.Collection.extend({...});
App.Todo.Views = Backbone.View.extend({...});
I personally prefer the App.[Module Name] structure over having my modules split up, but would like to know the benefits, if any, of having the different structures.
Which structure do you use, and how has it helped you over a different structure you may have seen or used in the past?
I like the approach described in this blog:
http://weblog.bocoup.com/organizing-your-backbone-js-application-with-modules/
If you are using requireJS you don't need/want to attach the models/views to a global namespace object attached to the window (no App.Views, App.Models). One of the nice things about using requireJS or a different AMD module loader is that you can avoid globals.
You can define a model like this:
define(['underscore', 'backbone'],
function(_, Backbone) {
var MyModel = Backbone.Model.extend({});
return MyModel;
});
Then you define a view:
define(['underscore', 'backbone', 'tpl!templates/someTemplate.html'],
function(_, Backbone, template) {
var MyView = Backbone.View.extend({});
return MyView;
});
Now you have a model and a view with no globals. Then if some other module needs to create one of these (maybe your App module), you add it to the define() array and you have it.

Backbone Marionette and ICanHaz (Mustache) templates configuration

I'm migrating a Backbone basic app to Marionette and I would like to use ICanHaz.js as a template system (based on Mustache).
I'm using AMD and Require.js and the only way to make ICanHaz.js working with it and Backbone was to use jvashishtha's version.
I first implemented the app in pure Backbone style.
In particular I used to load each template as raw strings with the Require.js' text plugin and then add the template to the ich object. This create a method in ich object that has the same name of the loaded template:
define([
'jquery',
'underscore',
'backbone',
'iCanHaz',
'models/Job',
'text!templates/Job.html'
], function( $, _, Backbone, ich, Job, jobTemplate) {
var JobView = Backbone.View.extend({
render: function () {
/* since the render function will be called iterativetly
at the second cycle the method ich.jobRowTpl has been already defined
so ich will throw an error because I'm trying to overwrite it.
That is the meaning of the following if (SEE: https://github.com/HenrikJoreteg/ICanHaz.js/issues/44#issuecomment-4036580)
*/
if (_.isUndefined(ich.jobRowTpl)){
ich.addTemplate('jobRowTpl', jobTemplate);
};
this.el = ich.jobRowTpl(this.model.toJSON());
return this;
}
});
return JobView;
});
So far so good. The problem comes with Marionette.
The previous code works fine in the Backbone version, but there is no need to define a render function in Marionette's views.
Marionette assumes the use of UnderscoreJS templates by default. Someone else has already asked how to use Mustache with Marionette.
From that answer I've tried to implement my solution. In app.js:
app.addInitializer(function(){
//For using Marionette with ICH
var templateName=''; //not sure if this would help, anyway it makes no difference
Backbone.Marionette.Renderer.render = function(template, data){
if (_.isUndefined(ich.template)){
//this defines a new template in ich called templateName
ich.addTemplate(templateName, template);
};
return ich.templateName(data);
}
But the console throws me:
Uncaught TypeError: Object #<Object> has no method 'templateName'
So the template has not been defined. Anyway, any hint if I'm in the right direction?
I think it's just a problem with your JS inside your renderer function.
This line:
return ich.templateName(data);
Will look for a template literally called "templateName"
What you want, since templateName is a variable is something like:
return ich[templateName](data);
Then it will interprete the value of the templateName variable instead.

Resources