1

I built a small javascript library I need to use inside a BackboneJS project. My problem is, I have an issue to use the library. I think I did something wrong, when I'm trying to access it, I got an "undefined".

Some code below, I simplified it.

The library looks something like that - myLibrary.js:

(function() {
    var myLibrary = this;

    var initialize = function() {
        console.log('initialize');
    };

    myLibrary.otherFunction = function() {
        console.log('otherFunction');
    };
    return myLibrary;
})();

I putted my library in my requirejs config:

requirejs.config({
    paths: {
        jquery: "js/jquery"
        myLibrary: "js/myLibrary"
    }, 
    shim: {
        myLibrary: {
            deps: ['jquery']
        }
    }
});

And I'm trying to use my library inside a BackboneJS view

define([
  'jquery',
  'backbone',
  'myLibrary'
], function($, Backbone, myLibrary){
    'use strict';

    return Backbone.View.extend({

        initialize: function() {
            console.log(myLibrary); 
            //myLibrary is undefined here!
            //I'd like to access myLibrary as an object 
            //to access my functions inside..
        }
    });
});

The library is loaded. I can see it in the Network tab of my developer bar.

If you have any idea what's wrong here?

Thanks.

1 Answer 1

4

The way you've got things right now, your myLibrary script is actually running, but the return value (return myLibrary;) is being discarded because it's not being assigned to anything. You can do one of two things:

You can assign the return value to something on the global object and update your shim config:

window.myLibrary = (function() {
    var myLibrary = this;

    var initialize = function() {
        console.log('initialize');
    };

    myLibrary.otherFunction = function() {
        console.log('otherFunction');
    };
    return myLibrary;
})();

requirejs.config({
    paths: {
        jquery: "js/jquery"
        myLibrary: "js/myLibrary"
    }, 
    shim: {
        myLibrary: {
            deps: ['jquery'],
            exports: "myLibrary"
        }
    }
});

Or, better yet, actually use define inside your library:

define(["jquery"], function ($) {
    var myLibrary = this;

    var initialize = function() {
        console.log('initialize');
    };

    myLibrary.otherFunction = function() {
        console.log('otherFunction');
    };
    return myLibrary;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.