RequireJS + BackboneJS - connect modules - backbone.js

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

Related

BackboneJS How to import module and insert in specific html element of main view

I have a Main view where I import external views(modules), fetch the collections and insert them as new Views inside specific HTML elements. But now I get an error I dont understand...
I have this view defined:
function (App, Backbone, auth) {
var userNav = App.module();
UserNav = Backbone.View.extend({
...
)}
return UserNav;
}
then in my Main view, I want to import the View userNav.
define(['app', 'backbone', 'modules/userNav'],
function (App, Backbone, UserNav,) {
var Main = App.module();
Main.View = Backbone.View.extend({
template: 'main',
...
afterRender: function(){
var userNav = new UserNav.View();
this.insertView('.usernav', userNav);
}
But I get Uncaught TypeError: undefined is not a function - and its referring to the line
var userNav = UserNav.View();
what is the issue here?
I guess that the problem is the UserNav.
try to define this as a module using this code.
define(['Backbone','App','auth'], function(Backbone,App, Auth){
var UserNav = Backbone.View.extend({
//Your code
)}
return UserNav;
});
This is the way that requireJs define a module.
Hope it helps.
new UserNav() instead of new UserNav.View()
UserNav is the View

Marionette CollectionView with requireJS: undefined is not a function

I will explain my problem with an example. I can make this piece of code work without any problem (using MarionetteJS v1.6.2):
http://codepen.io/jackocnr/pen/tvqHa
But when I try to use it with requireJs and I put it on the initialize method of a Marionette Controller, I'm Getting the following error:
Uncaught TypeError: undefined is not a function backbone.marionette.js:2089
The Error comes when I define the collection view:
var userListView = new UserListView({
collection: userList
});
I Can't figure out what is happening (this is the same code of the link above, but inside the controller initialize method)
define([
'jquery',
'underscore',
'backbone',
'marionette'
], function($,_,Backbone,Marionette){
var Controller = Backbone.Marionette.Controller.extend({
initialize: function(){
var User = Backbone.Model.extend({});
var UserList = Backbone.Collection.extend({
model: User
});
var UserView = Backbone.Marionette.ItemView.extend({
template: _.template($("#user-template").html())
});
var UserListView = Backbone.Marionette.CollectionView.extend({
tagName: "ul",
itemView: UserView,
initialize: function() {
this.listenTo(this.collection, "add", this.render);
}
});
// instances
var jack = new User({name: "Jack"});
var userList = new UserList(jack);
var userListView = new UserListView({
collection: userList
});
// add to page
$("#user-list").append(userListView.render().el);
$("#add-user").click(function() {
var andy = new User({name: "Andy"});
userList.add(andy);
});
},
});
return Controller;
});
instead of using Backbone.Marionette in main.js shim : { use Marionette
marionette: {
exports: 'Marionette',
deps: ['backbone']
},
Thus while declaring any marionette inheritance juste use Marionette instead of Backbone.Marionette as such
var Controller = Marionette.Controller.extend
var UserView = Marionette.ItemView.extend
var UserListView = Marionette.CollectionView.extend
For some reason the newer version or Marionette.js behave this way. I guest it produce less code.
I have replaced the Marionette 1.6.2 version with the 1.5, and now it works as it does the version without requireJs. So I think it's a release bug or something like that.
Seems to be working fine for me. I made a simple project here.

Issue related to rendering multiple views through a single view

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();
});

Require.js module not seeing Backbone Router.js

In this simple Require/Backbone app
https://github.com/thisishardcoded/require-prob
Why does app.js see Router but TestView.js not?
Here is the first line of app.js
define(['router'],function (Router) {
and here is the first line of TestView.js
define(['backbone','router'],function(Backbone,Router){
Check out the repo for full details, download, run and check console log if you feel so inclined
Thanks!
Jim
More: Ok, the answer is - because of the order in which it is loaded and even if that were altered I have a circular dependency don't I? TestView needs Router, Router needs TestView.
In which case the solution might be
var r=require('router);
r.navigate or whatever
but, that seems like a shame that Router is not directly accessible everywhere and, is the above method good practice anyway?
Surely it happens because of circular dependency. To resolve it, you either pass router to view's constructor and remove router dependency from view's module, or use require('router') in your view.
1st option, router.js:
app_router.on('route:test', function () {
var testView = new TestView({router: app_router});
testView.render();
})
1st option, view.js:
define(['backbone'], function(Backbone){
var TestView=Backbone.View.extend({
el: '#test',
initialize: function() {
// get router from constructior options
this.router = this.options.router
},
render: function(){
this.$el.html('<p>Foo!</p>');
console.log("TestView.js does not find 'Router',", this.router);
}
});
return TestView;
});
2nd option, view.js:
define(['backbone','router'], function(Backbone, router){
// at this point router module is not loaded yet so router is undefined
var TestView=Backbone.View.extend({
el: '#test',
initialize: function() {
// at this point router module is loaded and you may access it with require call
this.router = require('router');
},
render: function(){
this.$el.html('<p>Foo!</p>');
console.log("TestView.js does not find 'Router',", this.router);
}
});
return TestView;
});
2nd option is also described here: http://requirejs.org/docs/api.html#circular
You should define baseUrl property in your main.js file that contains RequireJS config.
In this way all paths to modules in your application will be relative to that baseUrl.
See:
http://requirejs.org/docs/api.html#jsfiles
http://requirejs.org/docs/api.html#config-baseUrl
I downloaded and inspected your code. Following could be the issues:
require.js only works with AMDs. Since backbone no longer supports AMD. You will need to use AMD enabled version of Backbone. You can get it here
TestView is the dependency in you Router. So it loads before the Router is loaded.
You might want to improve the coding pattern. Here is my suggestion:
App.js
define([
'backbone',
'router',
], function(Backbone, MainRouter){
'use strict';
var AppView = Backbone.View.extend({
initialize: function(){
App.router = new MainRouter();
Backbone.history.start();
}
});
return AppView;
});
Router.js
define([
'backbone',
'view/TestView'
], function(Backbone, TestView){
var Main = Backbone.Router.extend({
routes: {
'test': 'test'
},
test: function(){
new TestView({
// pass model or collection to the view
// model: new TestModel // remember to require
});
}
});
return Main;
});
EDIT
Listening to events:
// in main.js
var window.Vent = {};
_.extend(window.Vent, Backbone.Events);
// now in any view you can trigger a event
$('something').on('click', function(){
window.Vent.trigger('somethinghappened', this);
// this is reference to current object
});
// now in other view you can do
window.Vent.on('somethinghappened', this.run, this);
// this in the end is the reference we passed when event was triggered
run: function(obj){
//this function will run when the event is triggered
// obj is the object who triggered the event
}
PS: why do you want to use router in view?? I have built quite a few backbone apps. Never needed to do so.
You can use available Backbone.history.navigate to achieve your goal easier, because Router.navigate is a simple wrapper for it. Consider this part of Backbone source:
navigate: function(fragment, options) {
Backbone.history.navigate(fragment, options);
return this;
},

Handlebar compiled html not recognizing template function in backbone.js

The project I am on is currently using Backbone.js to create a website and is using Handlebars (http://handlebarsjs.com/) as the templating system. I am attempting to create a sub-view that gets values from a json document into a corresponding template and then return that to a parent view.
The problem I am running into is that when I use
Handlebars.Compile(referenceViewTemplate)
it then doesn't recognize the template function when I try to replace the tokens using
this.template({ identifier: value })
The template code is:
<div id="reference-template">
<div class="id">{{id}}</div>
<div class="reference">{{content}}</div>
</div>
The backbone model is:
define(['underscore','backbone'],
function(_, Backbone){
var reference = Backbone.Model.extend({
initialize: function(){}
});
return reference;
});
The backbone collection code is:
define(['underscore','backbone','models/reference'],
function(_, Backbone, Reference){
var References = Backbone.Collection.extend({
model: Reference,
parse:function(response){ return response; }
});
return new References;
});
The code in the parent view which calls the reference view is:
this.ref = new ReferenceView();
this.ref.model = this.model.page_refs; //page_refs is the section in the json which has the relevant content
this.ref.render(section); //section is the specific part of the json which should be rendered in the view
And the code in the ReferenceView is:
define([
// These are path alias that we configured in our bootstrap
'jquery','underscore','backbone','handlebars',
'models/reference','collections/references','text!templates/reference.html'],
function($, _, Backbone, Handlebars, Reference, References, referenceViewTemplate) {
var ReferenceView = Backbone.View.extend({
//Define the default template
template: Handlebars.Compiler(referenceViewTemplate),
el: ".overlay-references",
model: new Reference,
events:{},
initialize : function() {
this.model.bind('change', this.render, this);
return this;
},
// Render function
render : function(section) {
//this is where it says "TypeError: this.template is not a function"
$(this.el).append(this.template(References.get(section).get("content")));
return this;
}
});
I know this is a lot to read through and I appreciate anyone taking the time to do so, please let me know if there is anything else I can provide to clarify.
The answer is that apparently I was using the wrong function to compile the html. For some reason I typed in Handlebars.Compiler instead of Handlebars.compile
This hasn't solved all the problems in my project (template is being passed back now, but without the values entered), but at least it's a step forward.

Resources