Issue with this.$el.find in Backbone framework - backbone.js

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.

Related

Backbone Multiple Collection Fetch and Rendering

I am developing a Backbone application.
I have a view named as "Dashboard". In this dashboard View, I will be fetching two collections of data; one for the List of recent articles from the articles table and the other for the list of Authors from the authors table.
Please note that I have two different tables in mySQL Database, I use SlimPHP Api to make queries and retrieve data.
I am also using Handlebars templating Javascript library to compile the HTML.
Question:
My Question is that what is the best approach to make the two queries and then send both collections data to the Handlebars compile which will create the HTML (after looping through collection models) and eventually be taken into render function.
Here is what I have tried so far (Dashboard View Javascript File):
http://jsfiddle.net/n6c3q16r/2/
I tried to fetch two models data and pass it into the render function on line # 17 on jsFiddle:
this.$el.html(this.template(this.collection, this.topAuthorsCollection));
But this does not work.
Try this:
initialize: function() {
this.listenTo(this.topAuthorsCollection, 'reset', this.render);
this.topAuthors = new topAuthorsModel();
this.topAuthorsCollection = new topAuthorsCollection({model: this.topAuthors});
this.collection.fetch({
reset: true,
success: function() {
this.topAuthorsCollection.fetch({reset: true})
}
});
}
You can use promises. My personal favourite in such a scenario is jQuery.when
$.when(collection1.fetch(),collection2.fetch()).done(function(){
//Do stuff here
});
API - http://api.jquery.com/jquery.when/
Updated fiddle - http://jsfiddle.net/n6c3q16r/4/

How do you maintain view states with Marionette JS?

It seems that Marionette isn't designed to handle reusing views. What is an effective way to maintain view states (for all view types) since they're always being reconstructed?
My first thought was to capture state in the models, but I quickly parted with that idea as many views can reference the same model.
I did try reusing views in a couple of different fashions but wasn't confident what I was doing was correct. In each case, I felt like the Marionette methods I was overriding might break things (now and/or later).
I've found suggestions on how to accomplish this with pure Backbone, and also glanced at Giraffe which seems to handle state quite effectively, but I've yet to find a solution for Marionette.
An easy unsaved state system for getting data to the template is:
View.MyView = Marionette.ItemView.extend({
serializeData: function() {
return _.merge(this.model.toJSON(), this.options.state.toJSON());
},
});
var view = new View.MyView({
model: model,
state: new Backbone.Model(),
});
With a little more advanced version you can use the model events too:
View.MyView = Marionette.ItemView.extend({
initialize: function() {
var self = this;
this.options.state.on('change', function(event, data) {
if (_.isFunction(self[event])) {
self[event](data);
}
});
},
});
Then in your controller:
view.options.state.trigger('change', 'functionName', 'someData');
You can track your view states by using a ViewModel.
Sam talks a bit about this here: http://youtu.be/CTr-tTwRH3o

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.

Backbone - reading template data from DOM in View

I'm trying to figure out the best way for a backbone view to read template data. I'm using underscore templates.
I have a template defined in a script block on the page:
<script id="template" type="text/html">
This is my template
</script>
However, I'm having trouble reading in the template in certain parts of the view (I assume this is somethin g to do with el scoping). For example:
var SomeView = Backbone.View.extend({
tagName: 'div',
className: 'someClassName',
t1 : $('#template').html(),
initialize: function() {
var t1 = this.t1;
var t2 = $('#template').html();
...
},
...
t1 contains the correct template html, while t2 is null.
Why is this? and Where is the correct place in the view to read in this template from the DOM?
I'm trying to figure out the best way for a backbone view to read template data. I'm using underscore templates.
To answer that particular part of your question. May I suggest using a plugin in requirejs?
Since you run an app.js, I guess maybe you are using requirejs. I'm testing my luck here. My guess could be totally wrong. But in the case that you are, why not try to use the text! plugin from requirejs that reads in a file as string (your template) like so?
define(
['text!templates/template.html'], function(myTemplate){
});
So far, this works beautifully as far as my template goes. Never ran into a single problem with this method.
You'll be able to find this under here in the "Modularizing a Backbone View" section
The value of an object literal is evaluated immediately, so your jQuery selector for the template is returning empty. You need to wait until the DOM is ready to select the template.
See this article for more information:
http://lostechies.com/derickbailey/2011/11/09/backbone-js-object-literals-views-events-jquery-and-el/

Backbone Design

I'm just getting started with Backbone. I went through the first two PeepCode screencasts which were great and now I'm digging in on a quick detached (no server side) mock-up of a future app.
Here's what I'm looking to build (roughly). A series of five text boxes - lets call these Widgets. Each Widget input, when selected, will display a pane that shows Tasks associated with the Widget and allow the user to create a new Task or destroy existing Tasks.
At this point, I'm thinking I have the following models:
Widget
Task
The following collections:
Tasks
Widgets
The following views (this is where it gets hairy!)
WidgetListView
- Presents a collection of Widgets
WidgetView
- sub-view of WidgetListView to render a specific Widget
TaskPaneView
- Presented when the user selects a Widget input
TaskCreateView
- Ability to create a new Task associated with selected Widget
TaskListView
- Presents a collection of Tasks for the given widget
TaskView
- Displays Task detail - sub-view of TaskListView
Assuming that's reasonable, the trick becomes how to display a TaskPaneView when a WidgetView is selected. And futhermore, how that TaskPaneView should in turn render TaskCreateViews and TaskListViews.
The real question here is: Does one cascade render events across Views? Is it permissible for a Root view to know of sub-views and render them explicitly? Should this be event-driven?
Apologies if this is an open-ended question, just hoping someone will have seen something similar before and be able to point me in the right direction.
Thanks!
Definitely make it event driven. Also, try not to create views that are closely coupled. Loose coupling will make your code more maintainable as well as flexible.
Check out this post on the event aggregator model and backbone:
http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js/
The short version is you can do this:
var vent = _.extend({}, Backbone.Events);
and use vent.trigger and vent.bind to control your app.
Pre p.s.: I have made a gist for you with the code that I wrote below:
https://gist.github.com/2863979
I agree with the pub/sub ('Observer pattern') that is suggested by the other answers. I would however also use the power of Require.js along with Backbone.
Addy Osmani has written a few GREAT! resources about Javascript design patterns and about building Backbone applications:
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
http://addyosmani.com/writing-modular-js/
http://addyosmani.github.com/backbone-fundamentals/
The cool thing about using AMD (implemented in Require.js) along with Backbone is that you solve a few problems that you'd normally have.
Normally you will define classes and store these in some sort of namespaced way, e.g.:
MyApp.controllers.Tasks = Backbone.Controller.extend({})
This is fine, as long as you define most things in one file, when you start adding more and more different files to the mix it gets less robust and you have to start paying attention to how you load in different files, controllers\Tasks.js after models\Task.js etc. You could of course compile all the files in proper order, etc, but it is far from perfect.
On top of this, the problem with the non AMD way is that you have to nest Views inside of each other more tightly. Lets say:
MyApp.classes.views.TaskList = Backbone.View.extend({
// do stuff
});
MyApp.views.App = Backbone.View.extend({
el: '#app',
initialize: function(){
_.bindAll(this, 'render');
this.task_list = new MyApp.classes.views.TaskList();
},
render: function(){
this.task_list.render();
}
});
window.app = new MyApp.views.App();
All good and well, but this can become a nightmare.
With AMD you can define a module and give it a few dependencies, if you are interested in how this works read the above links, but the above example would look like this:
// file: views/TaskList.js
define([], function(){
var TaskList = Backbone.View.extend({
//do stuff
});
return new TaskList();
});
// file: views/App.js
define(['views/TaskList'], function(TaskListView){
var App = Backbone.View.extend({
el: '#app',
initialize: function(){
_.bindAll(this, 'render');
},
render: function(){
TaskListView.render();
}
});
return new App();
});
// called in index.html
Require(['views/App'], function(AppView){
window.app = AppView;
});
Notice that in the case of views you'd return instances, I do this for collections too, but for models I'd return classes:
// file: models/Task.js
define([], function(){
var Task = Backbone.Model.extend({
//do stuff
});
return Task;
});
This may seem a bit much at first, and people may think 'wow this is overkill'. But the true power becomes clear when you have to use the same objects in many different modules, for example collections:
// file: models/Task.js
define([], function(){
var Task = Backbone.Model.extend({
//do stuff
});
return Task;
});
// file: collections/Tasks.js
define(['models/Task'], function(TaskModel){
var Tasks = Backbone.Collection.extend({
model: TaskModel
});
return new Tasks();
});
// file: views/TaskList.js
define(['collections/Tasks'], function(Tasks){
var TaskList = Backbone.View.extend({
render: function(){
_.each(Tasks.models, function(task, index){
// do something with each task
});
}
});
return new TaskList();
});
// file: views/statistics.js
define(['collections/Tasks'], function(Tasks){
var TaskStats = Backbone.View.extend({
el: document.createElement('div'),
// Note that you'd have this function in your collection normally (demo)
getStats: function(){
totals = {
all: Tasks.models.length
done: _.filter(Tasks, function(task){ return task.get('done'); });
};
return totals;
},
render: function(){
var stats = this.getStats();
// do something in a view with the stats.
}
});
return new TaskStats();
});
Note that the 'Tasks' object is exactly the same in both views, so the same models, state, etc. This is a lot nicer than having to create instances of the Tasks collection at one point and then reference it through the whole application all the time.
At least for me using Require.js with Backbone has taken away a gigantic piece of the puzzling with where to instantiate what. Using modules for this is very very helpful. I hope this is applicable to your question as well.
p.s. please also note that you'd include Backbone, Underscore and jQuery as modules to your app too, although you don't have to, you can just load them in using the normal script tags.
For something with this kind of complexity, I might recommend using Backbone Aura, which has not yet had a stable release version. Aura essentially allows you to have multiple fully self-contained Backbone apps, called "widgets," running on a single page, which might help disentangle and smooth over some of your model/view logic.
From a classical MVC perspective, your views respond to changes in their associated models.
//initialize for view
initialize : function() {
this.model.on("change", this.render(), this);
}
The idea here is that anytime a view's model is changed, it'll render itself.
Alternatively or additionally, if you change something on a view, you can trigger an event that the controller listens to. If the controller also created the other models, it can modify them in some meaningful way, then if you're listening for changes to the models the views will change as well.
Similar answer to Chris Biscardi's. Here's what I have:
You create a global var Dispatcher (doesn't have to be global as long as it can be accessed from the scope of Backbone app):
Dispatcher = _.extend({}, Backbone.Events);
Dispatcher will help you execute subscribed callbacks with events that are not particularly triggered by changes in models or collections. And cool thing is that Dispatcher can execute any function, inside or outside Backbone app.
You subscribe to events using bind() in a view or any part of the app:
Dispatcher.bind('editor_keypress', this.validate_summary);
Then in another view or part of the app you trigger new event using trigger():
Dispatcher.trigger('redactor_keypress');
The beauty of using a dispatcher is its simplicity and ability to subscribe multiple listeners (e.g. callbacks in different Backbone views) to the same event.

Resources