Loading soundmanager2 with requirejs amd shim, logs undefined - javascript

So here's my main.js file (stripped out all my other scripts for clarity):
require.config({
paths: {
'soundmanager2': '../libs/soundmanager2/soundmanager2',
},
shim: {
'soundmanager2': {
'exports': 'soundManager'
}
}
});
Then i'm loading the library like so:
define(['jquery', 'underscore', 'backbone', 'utilities/events', 'utilities/helpers', 'soundmanager2'],
function($, _, Backbone, events, h, soundManager){
var TrackModel = Backbone.Model.extend({
initialize: function() {
console.log(soundManager);
}
});
return TrackModel;
}
);
The script is being downloaded - but when I log soundManager, I get undefined, no other errors.
Any ideas? Fear i'm missing something obvious..

I found the usage with requirejs in source code comment, but documentation no description. Here is the example.
define(['soundManager2'], function(SoundManager) {
var sound = SoundManager.getInstance();
sound.setup({
useHTML5Audio: true,
idPrefix: '',
onready: function() {},
ontimeout: function() {}
});
sound.beginDelayedInit();
})

This was an issue with the version of soundmanager2 - it has AMD baked in but I can't get it to export for some reason. I reverted to an earlier version, used the shim, and that fixed it!

Related

Using requirejs with retinajs

I am using requirejs and am calling in retinajs as a plugin. I am using the shim along with a jQuery dependancy:
....
'plugins/retina.min': {
'deps': ['jquery']
}
....
I then init my application:
requirejs(['./main'], function(App) {
App.init();
});
"main.js":
define(['jquery', 'foo', 'bar', 'plugins/domReady!', 'plugins/retina.min'], function($, foo, bar, retina) {....});
My logo on my page is getting updated correctly, however it seems I am running into a timing issue. Further down the page (or even subsequent page views) the script is getting executed before the page is ready.
Retina.js auto-exectues so there isn't a method to initialize per say. Is there a way to "call" a jquery plugin that auto-executes with require js?
This is wrong, but I think this is something along the lines of what I need:
define(['jquery', 'foo', 'bar', 'plugins/domReady!', 'plugins/retina.min'], function($, foo, bar, retina) {
var App = {
init: function() {
retina.init(); // This doesn't exist
<script src="/plugins/retina.js"></script> // Not even close to valid, but this is what I need.
}
};
return App;
});
Thank you for your time and suggestions!
Try this:
define(['jquery', 'foo', 'bar', 'plugins/domReady!'], function($, foo, bar) {
var App = {
init: function() {
require(['plugins/retina.min'], function(){
// This is straight from retina.js's source: https://github.com/imulus/retinajs/blob/master/src/retina.js#L142
if (Retina.isRetina()) {
Retina.init(window);
}
});
}
};
return App;
});

backbone require.js access to models

Im studying require and modular programming with backbone.
My question specifically is how can I access the models I have created in the View module as shown below from the main page, (example from the console), as is allways telling me undefined.
I understand that as its encapsulated in the view module, but is being hard to me to understand where I should create the instances of the model and collection as if I do it in init.js I get them to be undefined in the view module when i define collections or model.
If I instance them from model or collections modules I get a bunch of undefined errors
I have this init.js;
requirejs.config({
enforceDefine: true,
baseUrl: 'js',
urlArgs: "bust=" + (new Date()).getTime(),
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
}
},
paths: {
jquery: 'lib/jquery-1.10.2.min',
backbone: 'lib/backbone.min',
underscore: 'lib/underscore.min',
text: 'lib/require/text',
Plato: 'app/models/plato',
Carta: 'app/collections/carta',
MainView: 'app/views/mainView',
mainTemplate: 'app/templates/mainTemplate.html'
}
});
define(['jquery', 'underscore', 'backbone', 'MainView'], function($, _, Backbone, MainView) {
console.log(typeof $);
console.log(typeof _);
console.log(typeof Backbone);
var mainView = new MainView;
});
Then I have mainView.js as:
define(['backbone', 'text!mainTemplate', 'Plato', 'Carta'], function(Backbone, mainTemplate, Plato, Carta) {
var pizza = new Plato({precio:120, nombre:'pizza', foto:'n/a', ingredientes: 'harina, tomate, oregano', diabeticos:false}),
empanada = new Plato({precio:40, nombre:'empanada', foto:'n/a', ingredientes: 'harina, carne picada', diabeticos:false}),
lasagna = new Plato({precio:200, nombre:'lasagna', foto:'n/a', ingredientes: 'pasta, queso', diabeticos:false}),
carta = new Carta([pizza, empanada, lasagna]),
MainView = Backbone.View.extend({
tagName: 'div',
id: 'mainView',
events: {'click td': 'clickAction'},
collection: carta,
template: _.template(mainTemplate, this.collection),
initialize: function() {
this.render();
},
render: function() {
this.collection.each(function(item) {
console.log(item.toJSON() + item.get('nombre'));
this.$el.append( this.template( item.toJSON() ));
}, this);
$('#content').html(this.$el);
return this;
},
clickAction: function() {
alert(this);
}
});
return MainView;
});
I also have the model and collection modules if that helps you out to help me.
My main purpose would be to be able to access them and then put a listener or an on in the elements to be able to play with the data of those models.
Sorry If I am confused and mixing concepts with the variable scope of the modules using require.js and backbone, but I have read whatever I was able to find in the internet and Im still confused.
EDIT
Should I create and entire module just to instantiate them and then export the values as an object??
Should I create and entire module just to instantiate them and then
export the values as an object??
Yes. That's one way to accomplish what you are looking to do:
define(['backbone', 'text!mainTemplate', 'Plato', 'Carta', 'carta'],
function(Backbone, mainTemplate, Plato, Carta, carta) {
...
});
Where Carta is the collection module and carta is the object that contains the data.

RequireJS issues while loading and Hamljs

I am using requirejs + jquery + sammy.js + hamljs.
The template engine haml is not working : it runs sammy.haml, but Haml is defined for main.js but not for sammy.haml and cannot run in it. After the page is completely loaded, Haml exists for the console. Why Sammy does not get on well with HAML whereas it should be ?
requirejs.config({
baseUrl: '../../components/',
paths: {
dropkick: 'jquery-dropkick2/jquery.dropkick-1.0.0',
Ladda: 'Ladda/dist/ladda.min',
'jquery-autosize': 'jquery-autosize/jquery.autosize',
mixitup: 'mixitup/jquery.mixitup.min',
jquery: 'jquery/jquery',
sammy: 'sammy/lib/sammy',
'sammy.haml': 'sammy/lib/plugins/sammy.haml',
haml: 'haml/lib/haml',
browser: 'jquery.browser/jquery.browser.min'
},
shim: {
dropkick: {
deps: ['jquery']
},
browser: {
deps: ['jquery']
},
'sammy.haml': {
deps: ['haml']
}
}
});
requirejs(['jquery', 'haml'], function($, Haml) { // They are to be loaded first
requirejs(['sammy', 'sammy.haml', 'browser', 'markdown'], function(sammy, shaml, markdow) { // Then the others
console.log(Haml); // WORK
var app = sammy('#main', function() {
var self = this;
self.use(sammy.Haml);
self.get('/upload', function(context) {
context.app.swap('');
var s = context.render('app/templates/upload.haml', {});
s.appendTo(context.$element())
});
});
});
app.run();
});
});
Finally found the solution ! I defined window.Haml = haml in the main file, and modified sammy.haml.js to get window.Haml function instead of Haml function.

method won't trigger when using requireJS

I have some issue with some requireJS setup. I posted a question before but the scope of the latest changed now.
I have some
requirejs.config({
paths: {
'tmpl': 'vendor/upload/tmpl.min'
}
});
require({
paths: {
'videoupload': 'vendor/upload/jquery.ui.videoupload'
}
}, ['js/main_video.js'], function (App) {
App.initial_video_upload();
});
and finally in main_video.js :
define(['tmpl', 'videoupload'], function () {
function initial_video_upload(tmpl, videoupload) {
'use strict';
$('#videoupload').videoupload({
//...some code
});
}
return{
initial_video_upload: initial_video_upload
}
}
);
This code works perfectly if I don't use requireJS (loading classically each file). In fact, when this code is triggered, I keep on having a message Uncaught TypeError: Object [object Object] has no method 'tmpl', this method is defined in tmpl.min.js. And this method is invoked in vendor/upload/jquery.ui.videoupload, as so
$.widget('videoupload', {
//...
_renderVideo: function (video) {
this._templateElement().tmpl({
id: video.id,
name: video.title
}).appendTo(this._listElement()).find(
this.options['delete-selector']
);
return this;
},
//...
How can I manage that ? (I had earlier an error time out message for this method tmpl, but it disappeared now, so I don't think this is it)
In the configuration object, the path is not the full path to the JS file BUT the path to the directory containing the JS file, so you may want to do something like this in the main_video.js file:
requirejs.config({
paths:{
'upload': 'vendor/upload'
}
});
define(['upload/tmpl','upload/jquery_videoupload'],function(tmpl, videoupload) {
function initial_video_upload(tmpl,videoupload){
'use strict';
$('#videoupload').videoupload({
//...some code
});
}
return{
initial_video_upload: initial_video_upload
}
}
);
And in the main app:
requirejs.config({
paths:{
'js': 'path/to/your/js/folder'
}
});
require(['js/main_video'], function(App) {
App.initial_video_upload();
});
There's a problem in the questions code, so this:
define(['tmpl', 'videoupload'], function () {
should become this:
define(['tmpl', 'videoupload'], function (tmpl, videoupload) {
The first one doesn't expose loaded dependencies to local variables of closure function, so that's might be a problem, although it's not very clear if it's the only one, from the provided code.
I would also like to mention, that it's not a good thing to use multiple requre.js configs, if you're intended to use optimizer. The configs will be overwritten by the last one, so it's a good idea actually to have only one config for the whole project.
Like this:
requirejs.config({
paths: {
'tmpl': 'vendor/upload/tmpl.min',
'videoupload': 'vendor/upload/jquery.ui.videoupload'
}
});

Ember.application.create arguments

I am exploring one of Ember.js demo application and I find lot of arguments being passed to Ember.Application.create() in addition to usual VERSION and rootElement. The demo uses require.js which I understood is for AMD.
Does Ember.js does not take care by itself in its v1.0 to load javascripts based on need ? If it does so, I don't fully understand why should require.js be used with it..
Second, if require.js has a use case, what is the use of passing as many arguments like controller names and view names to Ember.Application.create() to bootstrap application.
// Define libraries
require.config({
paths:{
jquery:'lib/jquery-1.8.0.min',
handlebars:'lib/handlebars',
ember:'lib/ember_1.0pre',
ember_data:'lib/ember-data5',
text:'lib/require/text',
md5:'lib/md5',
//domready:'lib/require/domReady',
spin:'lib/spin'
},
shim:{
'ember':{
deps:[ 'jquery', 'handlebars'],
exports:'Ember'
},
'ember_data':{
deps:[ 'ember'],
exports:'DS'
}
},
waitSeconds:15,
urlArgs:"bust=" + (new Date()).getTime() //cancel caching for network requests,for development.
});
// Define application
define('application', [
'routes/app_router',
'controllers/application_controller',
'controllers/contacts_controller',
'controllers/contact_controller',
'controllers/edit_contact_controller',
'controllers/login_controller',
'views/application_view',
'views/contact_in_list_view',
'views/contacts_view',
'views/contact_view',
'views/edit_contact_view',
'views/login_view',
'models/contact',
'jquery',
'handlebars',
'ember',
'ember_data',
// 'domready',
'spin'
], function (Router,
ApplicationController,
ContactsController,
ContactController,
EditContactController,
LoginController,
ApplicationView,
Contact_In_List_View,
ContactsView,
ContactView,
EditContactView,
LoginView,
Contact )
{
return Ember.Application.create({
VERSION: '1.0.0',
rootElement:'#main',
// Load router
Router:Router,
//Load Controllers
ApplicationController:ApplicationController,
ContactsController:ContactsController,
ContactController:ContactController,
EditContactController:EditContactController,
LoginController:LoginController,
//Load associated Views
ApplicationView:ApplicationView,
Contact_In_List_View:Contact_In_List_View,
ContactsView:ContactsView,
ContactView:ContactView,
EditContactView:EditContactView,
LoginView:LoginView,
//Load Contact Model
Contact:Contact,
//Persistence Layer,using default RESTAdapter in ember-data.js.
store:DS.Store.create({
revision:5,
adapter:DS.RESTAdapter.create({
bulkCommit:false,
serializer:DS.Serializer.create({
primaryKey:function (type) {
return type.pk;
}
}),
mappings:{
contacts:Contact
},
namespace:'api' //you should change the first segment according to the application's folder path on the server.
})
}),
ready:function () {
}
});
}
);
Ex - application_controller.js
define('controllers/application_controller',
['ember' ],
function () {
return Ember.Controller.extend({
loggedin:false
});
}
);

Categories

Resources