Instantly share code, notes, and snippets.

Embed
What would you like to do?
yeomanのgenerator backboneを使って、handlebarsをtemplateにしたprojectでひな形作るまで

前提

node.js / npm / yeoman をinstall

手順

project作成

$ npm install -g backbone

$ mkdir my-project

$ cd my-project

$ yo backbone --template-framework=handlebars

generator

$ yo backbone:model blog

$ yo backbone:view blog

$ yo backbone:router blog

ソース

  • app/scripts/main.js

下の方に追記

require([
    'backbone', 'routes/blog'
], function (Backbone, BlogRouter) {
    new BlogRouter();
    Backbone.history.start();
});
  • app/scripts/routes/blog.js
/*global define*/

define([
    'jquery',
    'backbone',
    'models/blog',
    'views/blog'
], function ($, Backbone, Blog, BlogView) {
    'use strict';

    var BlogRouter = Backbone.Router.extend({
        routes: {
            "": "index"
        },

        index: function() {
            var blog = new Blog({name: "yamada"});
            var view = new BlogView({model: blog});
            $('body').html(view.render().$el);
        }
    });

    return BlogRouter;
});
  • app/scripts/views/blog.js
define([
    'jquery',
    'underscore',
    'backbone',
    'templates'
], function ($, _, Backbone, JST) {
    'use strict';

    var BlogView = Backbone.View.extend({
        template: JST['app/scripts/templates/blog.hbs'],
        render: function(){
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        }
    });

    return BlogView;
});
  • app/scripts/templates/blog.hbs
name is {{name}} !
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment