Skip to content

Instantly share code, notes, and snippets.

@rssilva
Created October 22, 2013 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rssilva/7105031 to your computer and use it in GitHub Desktop.
Save rssilva/7105031 to your computer and use it in GitHub Desktop.
A simple way to use Requirejs with Backbone, Underscore and Jquery. The different widgets and features can stay on different files and everything it'll be fine when you load require.js and the AppBootstrap.js files. After you can add the "page controller" script wich will load everything you need.
/*
* AppBootstrap.js - This file contains the path to Backbone, Underscore, Jquery and
*also the variables that which one will export
*/
/*global require*/
'use strict';
require.config({
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: [
'underscore',
'jquery'
],
exports: 'Backbone'
},
jquery: {
exports: '$'
}
},
paths: {
jquery: '/scripts/vendor/jquery',
backbone: '/scripts/vendor/backbone',
underscore: '/scripts/vendor/underscore'
}
});
require([
'backbone'
], function (Backbone) {
console.log('bootstraping app...')
//this code will add "_super" method. So we can call this._super('myMethod', args) instead
//this.constructor.__super__.myMethod.apply(this, {});
Backbone.Model.prototype._super = function(funcName){
return this.constructor.__super__[funcName].apply(this, _.rest(arguments));
}
});
/*
* Widget.js - Extends a Backbone Model
*/
define(['backbone'], function (Backbone) {
var Widget = Backbone.Model.extend({
initialize: function () {
console.log('init Widget')
this.myMethod();
},
myMethod: function () {
console.log('myMethod on Widget')
}
});
return Widget;
});
/*
* Page.js - Extends Widget
*/
define(['/scripts/Widget.js', 'backbone'], function (Widget, Backbone) {
var Page = Widget.extend({
initialize: function () {
console.log('init Page');
this._super('initialize', {});
this.myMethod();
},
myMethod: function () {
this._super('myMethod');
console.log('myMethod on Page');
}
});
return Page;
});
/*
* TestPage.js - Extends Page
*/
require(['/scripts/Page.js'], function (Page) {
var testPage = new Page();
});
/*
Page Examples
<!doctype html>
<html class="no-js">
<head>
<title>Main Page</title>
</head>
<body>
<div class="hero-unit">
<h1>Require.js Rules</h1>
</div>
<script data-main="scripts/testPage" src="/scripts/vendor/require.js"></script>
<script src="/scripts/AppBootstrap.js"></script>
<!--
<script src="/scripts/testPage.js"></script>
-->
</body>
</html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Other Page</h1>
</body>
<script src="/scripts/vendor/require.js"></script>
<script src="/scripts/AppBootstrap.js"></script>
<script src="/scripts/testPage.js"></script>
</html>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment