user1716672
user1716672

Reputation: 1073

Including a custom library of code in a Backbone.js view with require.js

I want to include a library of useful functions in my backbone view. I'm using require.js. My library looks like:

define(function (require) {

    "use strict";

    console.log('in the useful');

   var $ = require('jquery');

    function myFunction()
        {
        alert("Hello World!");
        }

});

and the view is like this:

 define(function (require) {

    "use strict";

    var $                   = require('jquery'),
       _                   = require('underscore'),
       UsefulFuncs         = require('app/utils/useful_func'),
       tpl                 = require('text!tpl/Register.html'),

       template = _.template(tpl),
       errors = [],

       Backbone            = require('backbone');

   return Backbone.View.extend({

       initialize: function() {

           this.render();

       },
       render: function () {
           this.$el.html(template());
           return this;
       },
       events: {
           'submit .register-form' : 'onSubmit',
       },
       onSubmit: function(e) {

        //UsefulFuncs.myFunction();
           myFunction();

       },


   });
});

But when i click "submit", I get "myFunction is not defined". Same when I try UsefulFuncs.myFunction();

So how can I access a library of my functions in backbone views?

Upvotes: 0

Views: 428

Answers (1)

Herman Tran
Herman Tran

Reputation: 1591

You have to return an object containing the function as a property from your utility module:

define(["jquery"], function($) {
    "use strict";
     var UsefulFuncs = {};
     console.log('in the useful');
     UsefulFuncs.myFunction = function() {
        alert("Hello World!");
     }
     return UsefulFuncs;
});

Then you can add more functions as an object property of UsefulFuncs.

Upvotes: 1

Related Questions