1

我注意到每次使用 require 时都需要先定义所有模块。就我而言,我现在不需要这样做,我只需要加载主干模板。

是否可以加载没有模块定义的模板?

这可能看起来像这样:

View = Backbone.View.extend({
    tagName: 'div',
    className: 'entry',
    initialize: function(model, response){
        console.log("View Intialized: "+this.model.get('id') )

        _.bindAll(this, "render") 
        this.model.bind('change', this.render)
        this.template = _.template( require( ['text!templates/users/view.html'] ) ) //would look something like this?
    },
    render: function(){
        var rendered = this.template( this.model.toJSON() ) 
        $(this.el).html( rendered ); 
        return this 
    }
})

在大多数情况下,我在一个文件中有多个视图,并且不确定模块定义将如何使用它。虽然,我会像上面一样简单的解决方案。

编辑:除了答案之外,这里还有一个更轻的解决方案http://coenraets.org/blog/2012/01/backbone-js-lessons-learned-and-improved-sample-app/最初加载所有模板这可能比根据需要加载更好。

4

1 回答 1

2

好的,首先感谢您提出这个问题:我为它写了一个(不好的)答案,然后意识到我不像我那样理解 Require ,它迫使我去教育自己更多:-) 希望现在我可以提供更好的答案。

有两种使用 require 的方法:

1) 同步:var baz = require('foo/bar')

2)异步:require(['foo/bar'], function(bar) {var baz = bar;}

问题是,您将两者与这一行结合起来:

this.template = _.template( require( ['text!templates/users/view.html'] )

您将依赖项以数组的形式提供给 require ,就好像您正在执行异步样式一样,但您希望它立即返回同步样式的模块。

解决方案很简单,要么:

A)预加载(使用定义调用或异步要求调用)您的模板,然后使用同步样式语法:

this.template = _.template( require('text!templates/users/view.html')
// NOTE: If you don't pre-load this won't work

或者:

B)使用异步风格:

require(['text!templates/users/view.html'], function(viewTemplate) {
    View = Backbone.View.extend({
    // rest of your code
    this.template = _.template(viewTemplate);
})
于 2012-12-27T01:59:49.033 回答