如何使用Batman.js将远程HTML模板加载到视图中

时间:2014-08-23 21:00:06

标签: javascript coffeescript batman.js

我试图在一个不是Ruby on Rails的框架上使用Batman.js。现在,我已经能够在将HTML内容直接设置到视图类中时呈现视图,例如:

class App.ContextMenuView extends Batman.View
  html: '<span>hello world</span>'

但是,我完全无法使用远程HTML模板呈现视图。根据我的理解,应该可以使用属性&#39;来源:但是,当我使用此属性时没有任何反应。

这是我非常短的申请的完整代码:

class window.App extends Batman.App
  @root   'home#index'
  @route  '/home', 'home#index"'

class App.HomeController extends Batman.Controller
  routingKey: 'home'

  index: (params) ->
    console.log 'poil'

class App.ContextMenuView extends Batman.View
  source: '_context_menu'

$(window).ready ->
  Batman.config.pathToHTML = '/templates' # The template can be found at //localhost/templates/_context_menu.html
  App.run()

在页面的HTML中的某个地方,有一个带有[data-view =&#34; ContextMenuView&#34;]属性的元素,蝙蝠侠正确检测到该属性,视图已正确实例化,但仍然:没有任何反应。

没有向网络服务器发出请求,来源&#39;属性似乎已完全被忽略......文档中没有任何内容可以提供有关该主题的详细信息。

我做错了什么?

编辑:

对于那些感兴趣的人,我通过重载Batman.View来解决这个问题:

class App.View extends Batman.View
  @template_cache: {}

  constructor: ->
    super
    @template_cache = App.View.template_cache
    @update_source()
    @observe 'source', (@update_source.bind @)

  update_source: ->
    @get_template_from_source() if @source?

  get_template_from_source: () ->
    if @use_cache and @template_cache[@source]?
      @set 'html', @template_cache[@source]
    else
      @fetch_template()

  fetch_template: () ->
    $.ajax {
        async:    not QUnit? # async should be false in the test environment
        dataType: 'html'
        url:      "#{Batman.config.pathToHTML}/#{@source}.html"
        success:  (@template_received.bind @)
        error:    (error) => console.log "Could not load template '#{@source}'", error
      }

  template_received: (html) ->
    @set 'html', html
    @template_cache[@source] = html if @use_cache

1 个答案:

答案 0 :(得分:0)

其他AJAX请求是否正常?如果没有,可能需要包含一个&#34;平台适配器&#34;,这是一堆实现AJAX&amp; amp;的代码。 Batman.js的DOM函数。您将在捆绑文件on the download page中找到适配器:

  • &#34; jQuery适配器&#34;取决于jQuery使用$.ajax$(...)来实现这些功能
  • &#34; solo adapter&#34;使用zest.js和reqwest.js来实现这些功能

这是关于Batman.js&amp ;;的另一个问题。 jquery:Using jQuery with Batman.js

这有帮助吗?

(如果是这样,它就是棺材里的钉子 - 我们一直在考虑让batman.js依赖于jQuery并删除那个&#34;抽象层次&#34;:S )