Backbone.js:separate the view ,collection,model to different js file,they could't recognize each other

后端 未结 2 460
夕颜
夕颜 2021-02-04 20:21

I use Backbone.js to create a web app,all the view,collection and model write into one js file,it success!

now I want separate them to different js files,just like:

2条回答
  •  梦如初夏
    2021-02-04 20:51

    You could also look at making you js files modular using Require.js. Works extremely well and will only load the views, models, and collections when they are needed. This is recommended if your application is quite large. It will prevent you from having to load all your scripts on page load. A quick backbone.js implementation would be as follows:

    define([
        'jquery',
        'underscore',
        'backbone',
        'models/post'
    ], function ($, _, Backbone, Post) {
        "use strict";
        var PostsCollection = Backbone.Collection.extend({
            model: Post,
            url: CONFIG.apiUrl + 'posts'
        });
        return PostsCollection;
    });
    

    The above is a collection module. You can see 'models/post' is pointing to the location of another module. jquery, underscore, and backbone were defined in my config so I just have to pass them in as opposed to pointing to their actual location. This is a quick intro, but if you are looking to separate your js files, Require.js is the way.

提交回复
热议问题