1

I have a project in Backbone and Im using require js (I dont have to much experience with require this is my first project with it , actually).

Now. On my home.js view I have a lot of functions like this

iScroll: function () {

                window.scrollers.myScroll = new iScroll(this.$('#products_container')[0], {
                    vScrollbar: true,
                    onScrollStart: function () {...........

swipeMobile: function () {
                $("#mobile_view").swipe({

                    swipe: function (event, direction, distance, duration, fingerCount) {
                        if (direction == "left") {....

I want to put all this functions in one separated module forexample "plugins" and to call function I need in my home.js view when I need it .

Im loading my templates on home view like this

define([
        'text!templates/about.html',
        'text!templates/home.html',
        'text!templates/product.html',
        'text!templates/contact.html',
        'collections/products'
    ],

    function (aboutTemplate, homeTemplate, productTemplate, contactTemplate, Products) {

Whats the easiest way to do this ?

1 Answer 1

2

If your collection of functions is an extension of a Backbone Model, Collection, or View, you can do the following:

define(['backbone'], function( Backbone ) {
    return Backbone.View.extend({
        customMethod: function() {
            return this;
        }
    });
});

Then just require the path to the file and you can use it like so:

require(['path/to/custom/view'], function( CustomView ) {
    var customview = new CustomView();
    customview.customMethod(); // returns the Backbone view
});

Edit: If you have some code that isn't a Model, Collection or View, you can do this instead (assumes that this is a module with no dependencies):

define(function() {
    var MyCustomHelper = function() {
        this.someattribute = true;
    };

    MyCustomHelper.prototype.customMethod = function() {
        return this.someattribute;
    };

    return MyCustomHelper;
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for this ! Btw how it would look if i dont work with backbone , if just wan to make simple module to require it on pages I need it ?

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.