javascript - 如何渲染路线 View ?

标签 javascript backbone.js requirejs backbone-routing

我的应用程序包含两个带有模板、路由器、模型和集合的 View 。

root
 js
  collections
   -collection.js
  models
   -model.js
  routers
   -router.js
  templates
   -add_item.html
   -list.html
  views
    -add_item.js
    -list.js
index.html

router.js ,我正在尝试导航到 subview 。

define([
    'jquery',
    'backbone',
    'views/item'
], function($, Backbone, ItemView) {
    'use strict';

    return Backbone.Router.extend({
        routes: {
            '': 'list',
            'list/add': 'addItem',
            'list/edit/:id': 'editItem'
        },

        addItem: function() {
            new ItemView();
        }
    });
});

通过查看调用堆栈,我发现我的路由器已触发。但我的 subview 的模板没有初始化。

item.js代码:

return Backbone.View.extend({
    template: _.template(itemTemplate),

    events: {
        'click #save': 'saveItem',
        'click #cancel': 'cancel'
    },

    initialize: function() {
        this.render();
    },

    render: function() {
        this.$el.html(this.template);
        return this;
    }
});

最佳答案

下划线的_.template

Underscore _.template function takes a template string as argument (and optionally a settings object) and returns a new pre-compiled template function which can take an object as an argument.

template: _.template(itemTemplate), // this returns a function, which is fine here.

这一行没问题,但下面这一行将返回的函数作为 HTML 内容:

this.$el.html(this.template); // a function reference as HTML?!

需要调用预编译模板函数来获取字符串:

this.$el.html(this.template());

主干 View 渲染

现在 View 的默认根元素 (el) 已正确填充模板内容。

<div>The div element is the default root element, this text is the template</div>

但是一旦呈现模板, View 的元素仍然在页面中。要使其成为页面的一部分,您可以:

  • 手动将 View 的 el 放入路由器中的另一个元素

    addItem: function() {
        var view = new ItemView();
        $("#content").html(view.render().el);
    }
    

    我将 view.render() 放在这里,因为 initialize 中的渲染不是我的首选模式,因为它限制了 View 的重用。但这实际上取决于人们的观点。

  • 传递 selector string或元素到 View 的 el 构造函数选项

    new ItemView({ el: '#the-view-element-id' });
    
  • 使用硬编码的 el 属性创建 View (这可以被上面的 el 选项覆盖)

    Backbone.View.extend({
        el: '#the-view-element-id',
        /* ... */
    

默认路线

如果您想默认使用 list 路由,您可以像这样创建 routes 对象:

routes: {
    'list/add': 'addItem',
    'list/edit/:id': 'editItem'
    // catch-all (default) route at the end
    '*anything': 'list',
},

其他信息:

关于javascript - 如何渲染路线 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41211863/

相关文章:

javascript - AngularJS 自定义指令 - Controller 变量 'crosstalk'

javascript - Requirejs:依赖项乱序加载

javascript - 无法理解 JavaScript 函数返回

javascript - 从动态输入字段 JavaScript 中读取文本

javascript - 避免 `fetch()` 将模型属性标记为已更改

javascript - Backbone 关系子模型类型

javascript - Marionette.js 集合在 Collection View 中未定义

javascript - 如何使用 requirejs 使 jQuery 插件可加载

node.js - Node 中的 R.js 和 Coffeescript

javascript - Modernizr 与 cssSandpaper?