如何与主干同步加载外部模板 [英] How to load external template synchronously with backbone

查看:21
本文介绍了如何与主干同步加载外部模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 phonegap、backbone.js 和 coffeescript 构建一个移动应用程序.我想做这样的事情:

I'm trying to build a mobile application with phonegap, backbone.js and coffeescript. I want to do something like this :

class MyApplication.Views.EntriesIndex extends Backbone.View
  template: load('my/template') //It will load the external file my/template.tpl

  render: ->
    $(@el).html(@template())
    this

我想同步加载.我已经看过 require.js 但我发现它对于这个简单的想法来说太复杂了.我看到我可以将 JST 用于 rails 应用程序,但我没有找到如何在没有 sprocket 的情况下使用它,而且我的应用程序必须只能在客户端工作.

I want to load it synchronously. I already seen require.js but I find it's too complicated for this simple think. I seen than I can use JST for a rails application but I don't find how to use it without sprocket and my application must to work on the client side only.

同步加载模板的更好方法是什么?

What is the better way to load templates synchronously?

我认为最好是预先加载它.

I think the better is to preload it.

我的应用程序将托管在客户端.

My application will be hosted on the client side.

推荐答案

我做到了:

class HomeView extends Backbone.View
  template: ->
    template = "views/home.html"
    cache = window.templates[template]
    return cache if cache

    cache = $.ajax(
      url: "views/home.html"
      async: false).responseText

    window.templates[template] = cache
    return cache

  render: ->
    @$el.html(@template())

而且,在我的应用程序的初始化中:

And, in my application's initalization :

window.templates = {}

所以我可以异步加载模板并缓存它.显然,我会进行一些重构,并且可能会将其放入 JQuery 函数中.

So I can load template asynchronously and cache it. Obviously, I will do some refactoring and, may be, place it into a JQuery function.

感谢您的帮助.

编辑

我更改了代码来执行此操作:

I change my code to do this :

class Loader
  @files: {}
  @load: (path) ->
    return @files[path] ||= $.ajax(url: path, async: false).responseText

现在我可以这样做了:

class HomeView extends Backbone.View
  template: ->
    Loader.load("views/home.html")

  render: ->
    @$el.html(@template())

这是javascript的版本:

This is the javascript's version :

var Loader;

Loader = (function() {

  function Loader() {}

  Loader.files = {};

  Loader.load = function(path) {
    var _base;
    return (_base = this.files)[path] || (_base[path] = $.ajax({
      url: path,
      async: false
    }).responseText);
  };

  return Loader;

})();

我可能会在github上发布代码...

I will probably publish the code on github...

这篇关于如何与主干同步加载外部模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆