如何同步加载外部模板与骨干

如何同步加载外部模板与骨干

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

问题描述

我试图建立与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应用程序,但我没有找到如何使用它无需链轮和我的应用程序一定要在客户端只工作。

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?

我觉得更好的是preLOAD它。

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())

而且,在我的应用程序的initalization:

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.

谢谢你的帮助。

修改

我改变我的code要做到这一点:

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...

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

08-20 17:26