1

我正在将 Backbone 基本应用程序迁移到 Marionette,并且我想使用ICanHaz.js作为模板系统(基于 Mustache)。
我正在使用 AMD 和 Require.js,而使 ICanHaz.js 与它和 Backbone 一起工作的唯一方法是使用 jvashishtha 的版本

我首先以纯 Backbone 风格实现了该应用程序。
特别是,我曾经使用Require.js 的文本插件将每个模板作为原始字符串加载,然后将模板添加到 ich 对象中。这将在 ich 对象中创建一个与加载的模板具有相同名称的方法:

define([ 
'jquery',
'underscore',
'backbone',
'iCanHaz',
'models/Job',
'text!templates/Job.html'

], function( $, _, Backbone, ich, Job, jobTemplate) {     
    var JobView = Backbone.View.extend({
        render: function () {
             /* since the render function will be called iterativetly  
                at the second cycle the method ich.jobRowTpl has been already defined
                so ich will throw an error because I'm trying to overwrite it.
                That is the meaning of the following if (SEE: https://github.com/HenrikJoreteg/ICanHaz.js/issues/44#issuecomment-4036580)
             */
            if (_.isUndefined(ich.jobRowTpl)){ 
                ich.addTemplate('jobRowTpl', jobTemplate);
            };

            this.el = ich.jobRowTpl(this.model.toJSON());
            return this;
        }
    });
    return JobView;

});

到现在为止还挺好。问题来自木偶。
之前的代码在 Backbone 版本中运行良好,但不需要在 Marionette 的视图中定义渲染函数。
Marionette 默认使用 UnderscoreJS 模板。其他人已经问过如何将 Mustache 与 Marionette 一起使用
从那个答案我试图实施我的解决方案。在 app.js 中:

app.addInitializer(function(){

  //For using Marionette with ICH
  var templateName=''; //not sure if this would help, anyway it makes no difference
  Backbone.Marionette.Renderer.render = function(template, data){
    if (_.isUndefined(ich.template)){ 
          //this defines a new template in ich called templateName
          ich.addTemplate(templateName, template);
    };
    return ich.templateName(data);
  }

但是控制台抛出了我:

Uncaught TypeError: Object #<Object> has no method 'templateName' 

所以模板还没有定义。无论如何,如果我的方向正确,有什么提示吗?

4

1 回答 1

3

我认为这只是渲染器函数中的 JS 的问题。

这一行:

返回 ich.templateName(data);

将寻找一个字面上称为“templateName”的模板

你想要什么,因为 templateName 是一个变量,类似于:

return ich[templateName](data);

然后它将解释 templateName 变量的值。

于 2013-01-18T08:19:56.453 回答