为什么使用 backbone 不显示 <h1> 标签?

why <h1> tag is not display using backbone?

我正在尝试使用 backbone js 加载一个 html 文件并需要 js 文件。我可以调用视图的初始化函数但无法加载那个 html 文件这是我的代码

define([
    'jquery',
    'underscore',
    'backbone',

    'text!templates/stats.html'
], function ($, _, Backbone, statsTemplate) {
    'use strict';
    var AppView = Backbone.View.extend({

        // Instead of generating a new element, bind to the existing skeleton of
        // the App already present in the HTML.
        el: '#todoapp',

        // Compile our stats template
        template: _.template(statsTemplate),

        // Delegated events for creating new items, and clearing completed ones.
        events: {

        },

        // At initialization we bind to the relevant events on the `Todos`
        // collection, when items are added or changed. Kick things off by
        // loading any preexisting todos that might be saved in *localStorage*.
        initialize: function () {


   alert('-in--')
        },

        // Re-rendering the App just means refreshing the statistics -- the rest
        // of the app doesn't change.
        render: function () {

        }
        // Add a single todo item to the list by creating a view for it, and
        // appending its element to the `<ul>`.



    });

    return AppView;

})

我在 initialize 函数中收到无法加载 html 文件的警报

这是我的代码 http://plnkr.co/edit/rhoE1H9A8nfu6II64aEo?p=preview

感谢您抽出宝贵时间设置一个工作示例。

不幸的是 Backbone 并没有给你很多免费的东西,所以有一些手动步骤可以让它工作:

  1. 添加一个 <div id="todoapp"></div> 到 index.html 因为你用 el: '#todoapp' 定位它但它不存在。

  2. 执行 template: _.template(statsTemplate) 将 return 模板的编译版本(作为函数)。然后,您需要像调用函数一样调用它,可选择传入上下文,以便模板可以呈现动态数据。例如this.template().

  3. render 方法不会被自动调用,所以当您准备好呈现视图时(通常是立即呈现,但也可能在 AJAX 响应之后)您需要打电话给 this.render()。在你的情况下直接 initialize.

  4. 最后,在 render 中,您可以将呈现的模板附加到视图的元素:this.$el.html(this.template());

更新示例:http://plnkr.co/edit/6HyOhuQ7LGL91rS8slJX?p=preview

我建议您使用这种常见的渲染流程创建一个 BaseView,这样您就不必每次都重复。在 BaseView 中设置子视图的概念也是一个好主意,子视图在调用父级 remove 时正确清理,并在调用父级 render 时重新呈现。

下面是一个使用 BaseView 的例子:http://jsfiddle.net/ferahl/xqxcozff/1/