Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 句柄:从帮助程序返回哈希_Javascript_Backbone.js_Coffeescript_Handlebars.js - Fatal编程技术网

Javascript 句柄:从帮助程序返回哈希

Javascript 句柄:从帮助程序返回哈希,javascript,backbone.js,coffeescript,handlebars.js,Javascript,Backbone.js,Coffeescript,Handlebars.js,我可以从车把助手处返回哈希吗?我试过这个: 在我看来: initialize: -> super this.hash = {key1: 'test1', key2: 'test2'} Handlebars.registerHelper 'show', => return this.hash {{show.key1}} this.showAttributes = {title: 'title1', author

我可以从车把助手处返回哈希吗?我试过这个:

在我看来:

    initialize: ->
      super
      this.hash = {key1: 'test1', key2: 'test2'}
      Handlebars.registerHelper 'show', =>
        return this.hash
{{show.key1}}
      this.showAttributes = {title: 'title1', author: 'author1'}

      Handlebars.registerHelper 'show', (cond) =>
        return cond.fn(this.showAttributes)
{{#show}}
    {{title}}
    {{author}}
{{/show}}
在模板中:

    initialize: ->
      super
      this.hash = {key1: 'test1', key2: 'test2'}
      Handlebars.registerHelper 'show', =>
        return this.hash
{{show.key1}}
      this.showAttributes = {title: 'title1', author: 'author1'}

      Handlebars.registerHelper 'show', (cond) =>
        return cond.fn(this.showAttributes)
{{#show}}
    {{title}}
    {{author}}
{{/show}}

我做错了什么?谢谢

车把将看到:

{{show.key1}}
试图访问
show
变量的
key1
属性时,它不会知道在这种情况下
show
应该指向您的
show
助手。这只是车把语法的一部分,我认为你对此无能为力

但是,您可以将
key1
作为参数传递给
show
助手。如果按以下方式定义辅助对象:

Handlebars.registerHelper 'show', (key, context) =>
    @hash[key]
{{show "key1"}}
然后像这样使用它:

Handlebars.registerHelper 'show', (key, context) =>
    @hash[key]
{{show "key1"}}
然后你会得到你期望的结果


演示:

找到了另一种方法。您可以将上下文传递给条件帮助器,如下所示:

Handlebars.registerHelper 'show', (key, context) =>
    @hash[key]
{{show "key1"}}
助手:

    initialize: ->
      super
      this.hash = {key1: 'test1', key2: 'test2'}
      Handlebars.registerHelper 'show', =>
        return this.hash
{{show.key1}}
      this.showAttributes = {title: 'title1', author: 'author1'}

      Handlebars.registerHelper 'show', (cond) =>
        return cond.fn(this.showAttributes)
{{#show}}
    {{title}}
    {{author}}
{{/show}}
在模板中:

    initialize: ->
      super
      this.hash = {key1: 'test1', key2: 'test2'}
      Handlebars.registerHelper 'show', =>
        return this.hash
{{show.key1}}
      this.showAttributes = {title: 'title1', author: 'author1'}

      Handlebars.registerHelper 'show', (cond) =>
        return cond.fn(this.showAttributes)
{{#show}}
    {{title}}
    {{author}}
{{/show}}
很好用