【问题标题】:How to load a remote HTML remplate into a view using Batman.js如何使用 Batman.js 将远程 HTML 模板加载到视图中
【发布时间】:2014-08-23 21:00:05
【问题描述】:

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

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

但是,我完全无法使用远程 HTML 模板呈现视图。据我了解,应该可以使用属性'source':但是,当我使用此属性时,什么都没有发生。

这是我非常简短的应用程序的完整代码:

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="ContextMenuView"] 属性的元素,蝙蝠侠正确检测到该属性,视图已正确实例化,但仍然:没有任何反应。

没有向网络服务器发出请求,'source' 属性似乎已被完全忽略...文档中没有任何内容提供有关该主题的更多详细信息。

我做错了什么?

编辑:

对于那些感兴趣的人,我通过重载 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

【问题讨论】:

    标签: javascript coffeescript batman.js


    【解决方案1】:

    其他 AJAX 请求是否正常?如果没有,可能需要包含一个“平台适配器”,这是一组为 Batman.js 实现 AJAX 和 DOM 功能的代码。您会在捆绑文件on the download page 中找到适配器:

    • “jQuery 适配器”依赖于 jQuery 使用 $.ajax$(...) 来实现这些功能
    • “solo adapter”使用 zest.js 和 reqwest.js 来实现这些功能

    这是关于 Batman.js 和 jquery 的另一个问题:Using jQuery with Batman.js

    这有帮助吗?

    (如果是这样,那就是棺材上的钉子——我们一直在考虑让 batman.js 依赖于 jQuery 并删除那个“抽象级别”:S)

    【讨论】:

      猜你喜欢
      • 2017-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 2016-04-04
      • 2014-01-16
      相关资源
      最近更新 更多