How to load external template synchronously with backbone

后端 未结 3 1902
猫巷女王i
猫巷女王i 2021-01-16 19:46

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

class MyApplication.Views.EntriesIn         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-01-16 20:00

    I did this :

    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 = {}
    

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

    Thanks for yours helps.

    Edit

    I change my code to do this :

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

    Now I can do this :

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

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

    I will probably publish the code on github...

提交回复
热议问题