RequireJS loads scripts before the view is initialized - backbone.js

I have a Backbone view as a requirejs module. The problem is that requirejs load the http://localhost/remote/script/here.js before the view is even initialized. Is it because the script isn't inside a requirejs module?
define([
'jquery',
'undescore',
'backbone',
'http://localhost/remote/script/here'
], function($, _, Backbone, Luajs){
var View = Backbone.View.extend({
initialize : function(options) {
},
render : function() {
this.$el.html('<p>my view</p>')
return this;
}
});
return View;
});

The array you have as the first argument to define is the depedencies of your view. So yes it is loaded and parsed before the View.
Also note that unless you use modified versions of backbone and underscore, they ar not AMD compliant. You will need to wrap them with a plugin to load them properly.

you try to define the view Backbone after the load the module.
You can do this, in the define () method of RequireJS. The array of this function contains parameters that defines module dependencies.

Related

how can I use external templates with Marionette Backbone

How exactly do I use an external template for my Marionette ItemView?
I read so many 'methods' I can't get any of them working...
JST Method ... I'm not on rails so can't use this
Backbone.Marionette.Renderer.render = (template, data) ->
path = JST["backbone/apps/" + template]
unless path
throw "Template #{template} not found!"
path(data)
RequireJS Method ... I'm not using require js
var tpl = require(inject[this.templateName]);
this.template = _.template(tpl);
What method should I be using?
I use Handlebars for my templating engine and hbs to retrieve the precompiled resource via require.js, that way all I have to do is define the template and set it as the ItemView's template; marionette does the rest.
Here's an example
View - welcome.js
define([
'app',
'jquery',
'backbone',
'marionette',
'hbs!templates/welcome'
],
function(App, $, Backbone, Marionette, template) {
return Backbone.Marionette.ItemView.extend({
template: template,
});
});
Template - welcome.html
<div>
<h1>Hello World</h1>
</div>
If you're not using handlebars, or can't use hbs, then something similar can be done with text.js - https://github.com/requirejs/text

Angular NgResource : Initialize error

i have a weird problem regarding angular resource. when i try to define it it causes the app to create an error. i dunno but is this the correct style of defining an angular Resource? tIA
main.js
'use strict';
require.config({
paths: {
jquery: 'libs/jquery/jquery-1.9.1',
angular: 'libs/angular/angular.min',
ngResource: 'libs/angular/angular-resource.min'
},
shim: {
angular: {
exports: 'angular'
},
resource : { deps : ['angular'], 'exports' : 'ngResource'},
}
});
require([
'jquery',
'angular',
//'ngResource',
'app',
'routes',
],
function ($, angular, app, routes) {// set main controller
$(function(){
var $html = $('html');
angular.bootstrap($html, [app['name']]);
$html.addClass('ng-app');
});
});
Just to help out those users who are not familiar with the code above; The code shows RequireJS configuration and initialization structure, and only a small part at the end is the actuall AngularJS code.
You have correctly configured RequireJS to include ngResource before initialization, but you didn't actually tell Angular to use it.
I'm not sure what app['name'] stands for, but your angular bootstrap call should include the ngResource module:
angular.bootstrap($html, ['ngResource']);
And, btw, I don't think you need to add the class ('ng-app') at the end.
In your callback when all resources are loaded, try to explicitly define the modules and dependancies before bootstrapping, like this:
angular.module('fooApp', ['ngResource']); // Module name and list of dependancies.
angular.bootstrap(document, 'fooApp');
There is no need to manually add the ng-app class, when this class is used to do bootraping automatically, witch is not what you want. You want to load the applicatiopns module when all scripts are loaded, with the ngResource module as a dependancy.
Hope this helps.

Where's the Backbone require.js dependency being resolved in this example?

In Addy Osmani's ToDo MVC example for require.js + Backbone: https://github.com/addyosmani/todomvc/blob/gh-pages/dependency-examples/backbone_require/js/main.js, he's using
Backbone.history.start() // line #31
without actually requiring Backbone. How/why does this work? Is the shim enabling this? Or am I missing something obvious?
If you have a look in the code, view/app.js is actually requiring Backbone.
And the backbone shim is exporting the global Backbone variable.
If no other modules will actually require the shim, it won't be loaded, so it won't be accessible.
You can try to remove the 'views/app' requirements in main.js to see for yourself.
As #ChristiMihai mentioned, Backbone created a global Backbone object, correct. Let me give you an example of what I do in my Require.js / Backbone / Handlebars app:
First, I include Require config in <head>:
var require_config = {
baseUrl: "/javascripts",
waitSeconds: 5,
paths: {
'cdnjs': 'http://ajax.cdnjs.com/ajax/libs',
'aspnetcdn': 'http://ajax.aspnetcdn.com/ajax',
'cloudflare': 'http://cdnjs.cloudflare.com/ajax/libs',
'local': '/javascripts'
}
}
if (typeof require !== 'undefined') {
require.config(require_config);
} else {
var require = require_config;
}
After that I bootstrap a require module, e.g:
define([
'app'
],
function() {
console.log('Homepage module');
/*
... this is the meat of your app...
you can add other dependencies beside `app` too
*/
});
Now app is the main dependency which resolves via baseUrl to /javascripts/app.js and includes all necessary deps in order, and looks like this:
define([
'order!cdnjs/json2/20110223/json2',
'order!cloudflare/underscore.js/1.3.1/underscore-min',
'order!cloudflare/backbone.js/0.9.2/backbone-min',
'order!handlebars/handlebars-1.0.0.beta.6.min',
'order!lib/ns',
'bootstrap'
], function(){});

Requirejs2: How to handle own files?

I have configured requirejs to load the core libs (jquery, underscore, backbone).
Now I would like to add my backbone models, controllers, views, etc to be loaded asyncronly
I found a lots of tutorials to this topic and lots of "ready" boilerplates unfortunatly I mentioned that most approaches are depreceated or rather complicated (even there are better approaches).
One example is how I configured requirejs for the main libs:
https://stackoverflow.com/a/10914666/1309847
So how do I load Backbone Views, Models, Collections, Routers, Controllers and Templates with a simple and valid Requirejs configuration?
I followed youre advice but get some strange error
main.js
require.config({
paths: {
jquery: 'vendors/jquery/jquery',
underscore: 'vendors/underscore/underscore',
backbone: 'vendors/backbone/backbone'
},
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
}
}
});
require(['app'], function(app){
});
app.js
define(['jquery', 'underscore', 'backbone'], function($, _, Backbone){
var Message = new Backbone.Model.extend({
//idAttribute: '_id',
//defaults: { body: '' }
//url: function(){ return this.id ? '/messages/' + this.id : '/messages'; }
});
var newMessage = new Message({ body: 'hi' });
newMessage.save();
});
The error occours in app.js:
Uncaught TypeError: Object [object Object] has no method 'apply'
When I comment the new Backbone.Model.extend part I don't get any error anymore.
in my experience, the best way to bootstrap your application is by creating a Backbone.Router. So you can associate urls with your application functionality.
If you are using RequireJS+Backbone, you probably have a main.js where RequireJS is configured (paths, shims, etc). The first call to "require" is used to load a initial script in order to bootstrap the whole app.
For example:
/**
* main.js - RequireJS bootstrap
*/
require.config({
paths: {
//your paths
},
shim: {
//your shims
}
});
require(
[
'app' //app.js is at the same directory as main.js
],
function(app) {
app.init();
}
);
then in app.js you can create a new Router instance, or you can just start creating Views and Models.
For further reference: http://addyosmani.github.com/backbone-fundamentals/
So as I have now understood right: You have to wrap a requirejs function around youre own custom js file.
The function is called define. The first parameter is an array of the dependencies which you have defined in the main.js file or a relative path to another custom js from you.
The second parameter is the callback which holds the original file. Important is that you return the object, function, array or variable which you want to share.
The whole thing looks like this:
define(
['underscore', 'backbone'], // the dependencies (either relative paths or shortcuts defined in main.js
function(_, Backbone){ // the return statement of the deps mapped to a var
var MessageModel = Backbone.Model.extend({ // the original code, file
defaults: { body: '' },
initialize: function(){}
});
return MessageModel; // the return statement, sharing the "final result", sometimes you return the initialize parameter
});
The same for a collection wrapping the models:
define(
['jquery', 'underscore', 'backbone', 'models/message_model'], // deps and the last one is the relative path
function($, _, Backbone,MessageModel){ // same as above explained
var MessageCollection = Backbone.Collection.extend({
model: MessageModel,
initialize: function(){}
});
return MessageCollection;
});
I now only have to figure out how I can bootstrap to whole application. But I think I need more knowledge of backbone to do this :)

BackboneJS + Requirejs: Backbone is null issue

In the router.js. The firebug console alerts Backbone is null there. Why???
app.js
define([
'order!jQuery',
'order!Underscore',
'order!Backbone',
'order!router' // Request router.js
],
function($, _, Backbone, Router){
App = {
initialize: function() {
console.log("app.js initalize");
Router.initialize();
}
};
return App;
});
router.js
define([
'order!Underscore',
'order!Backbone'
],
function(_, Backbone){
var AppRouter = Backbone.Router.extend({
// Console shows Backbone is null here, why?
// I'm sure the config is correct.
routes: {
'*actions': "defaultAction"
},
defaultAction: function(actions){
// We have no matching route, lets just log what the URL was
console.log('No route:', actions);
}
});
var initialize = function(){
console.log("Router initialize");
var app_router = new AppRouter;
Backbone.history.start();
};
return {
initialize: initialize
};
});
Backbone does not support the AMD and it doesn't register as module. When required it registers normally as a global Backbone object, also since 1.3 Underscore doesn't support AMD neither and if you will require Backbone and Underscore under Backbone and _ namespaces they will overwrite its values in this modules scope to undefined cause of that.
jQuery supports AMD but it also registers itself as a global instance. Basically it means that you don't need to require jquery, underscore and backbone multiple times - it's enough if you do it once in your requirejs main script
The alternative is to hack the backbone.js library.
Note: This will allow you to reference Backbone.js and underscore.js library within your require.js defines, but it will not stop them from being added to the global namespace/window object. This requires a little more hacking.
Find:
(function(){var l=this,y=
Replace it with:
define('backbone',['underscore','jquery'],function(_,$){
var l = this;
(function(){var y=
Add this to the bottom of the page:
return l.Backbone;
});
Then do the same for underscore.js
Prefix the beginning with:
define('underscore',function(){
Add to the bottom of the page:
return this._;
});

Resources