Backbone.js & require.js: how do I transform my models, views and collections to require.js modules?

前端 未结 2 764
滥情空心
滥情空心 2021-01-31 11:19

I am working on a javascript app with backbone.js, that said, for ease of development I structure my files this way

app
 |
 + views
 |    L movieRow.js
 |    L m         


        
2条回答
  •  感动是毒
    2021-01-31 11:44

    The key to understanding require (at least in my small brain) is to remember that what you return from the function will be available to other modules that pull in (or require) this module. So in the code below, I need jquery and backbone (jquery is a special case handled by "require-jquery"). When those 2 are available it will call my function and that function will return the View constructor that I created.

    define([    
        'jquery'
        'libraries/backbone'
    ], function ($) {
            var MovieRow = Backbone.View.extend({
                render: function () {
    
                    return this;
                }
            });
    
            return MovieRow;
    });
    

    Then you might write something like this to your page. Note that jquery is the first required item in the array. This corresponds to the first parameter in my function. The View is 2nd and the Model is 3rd. Then I can use the return value from my "define" code above which is the constructor.

    require({
        baseUrl: '/'
    },[
        'jquery',
        'app/views/movieRow',
        'app/models/movie',
        'libraries/backbone'
    ], 
    function ($, MovieRowView, Movie) {
        var view = new MovieRowView({model : new Movie());
        $('body').append(view.render().el);        
    });
    

    Hope this is helpful... We've been loving Backbone and Require :)

提交回复
热议问题