Requirejs加载模板没有模型定义



我注意到,每次使用时,您都需要首先定义所有模块。就我而言,我现在不需要现在就这样做,我只需要加载模板作为骨干即可。

是否可以使用模块定义加载模板?

看起来像这样的东西:

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 
    }
})

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

模板最初可能比根据需要加载更好。

好吧,首先,谢谢你问这个问题:我为此写了一个(不好的)答案,然后意识到我不像我那样理解,这迫使我要多教育一些:-)希望现在我可以提供更好的答案。

有两种使用方法:

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

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

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

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

您将依赖项作为数组所需的需要,就好像您正在执行异步风格一样,但是您希望它立即返回模块,同步。

解决方案很简单,要么:

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);
})

最新更新