Structing a backbone.js application

I have a backbone.js application with multiple models, views, collections and templates (in a script tag with type text/template with an ID which the views use to load the template in using _.template($(id).html())).

Currently, all of the above are in a single file, which makes it quite ugly. This is an offline application (ie, its loaded from the local filesystem and talks to a web server which allows cross-origin requests). I've been trying to figure out how to move the views, models and templates to separate files, I tried just moving the views and models out to views.js and models.js, but the views depend on the templates, and the templates can't be put into views.js (as its a JS file, and therefore can't have script tags..).

My only solution at this point seems to be moving the templates into global variables, which would be fine except for the javascript string escaping/multi line strings that would be required..

How is this usually handled?

Thanks!


Use RequireJS to package your views and models up into modules, and RequireJS will take care of the dependency resolution for you. You can get down to one view or model per file that way, too, instead of putting them all in one views.js or models.js.

Then, use the text! plugin to store your templates in text files, and require them like normal modules.

define(function (require, exports, module) {
  var templateText = require("text!./person.tmpl");
  var $ = require("jquery");

  exports.PersonView = Backbone.View.extend({
    render: function () {
        doStuffWith(_.template(templateText));
    }
  });
});

Take a look at these starter applications that use Backbone and RequireJS.

This one has Backbone.LocalStorage in it, which could help you with your offline stuff.

https://github.com/jcreamer898/Savefavs

This other one is just a simple starter for building an app...

https://github.com/jcreamer898/RequireJS-Backbone-Starter

They way you can handle templates with is...

define([
        'jquery', 
        'backbone',
        'underscore', 
        'models/model',
        'text!templates/main.html'], 
function($, Backbone, _, model, template){
    var MyView = Backbone.View.extend({
        initialize: function(){
            this.template = _.template(template);
        },
        render: function(){
            this.template(model);
        }
    });
    return new MyView();    

});


You might want to check out the Backbone boilerplate. This add a nice modular structure to your backbone app without polluting the global namespace, and provides a simple template caching.

It's really easy to change the template renderer to someting different that JST. Even if the general idea can be followed without any server side requirements, the boilerplate provides a basic node.js app as well.

链接地址: http://www.djcxy.com/p/66830.html

上一篇: backbone.js视图在模型获取之前呈现

下一篇: 构建backbone.js应用程序