2016-01-07 50 views
0

我对角度和骨干等东西很陌生,并且试图更好地理解结构。我构建了一些视图,但如果我在模板块中留下任何空格,它会打破一切。如何为骨干视图制作外部模板

var HomeView = Backbone.View.extend({ 
     template: '<h1>Home</h1><p>This is the first test. I think this is the way.</p>', 
     initialize: function() { 
      this.render(); 
     }, 
     render: function() { 
      this.$el.html(this.template); 
     } 
    }); 


var AboutView = Backbone.View.extend({ 
     template: '<h1>About</h1><p>This is the second test. I think this is the way.</p>', 
     initialize: function() { 
      this.render(); 
     }, 
     render: function() { 
      this.$el.html(this.template); 
     } 
    }); 

var CoolView = Backbone.View.extend({ 
     template: '<h1>Cool</h1><p>This is the third test. I think this is the way.</p>', 
     initialize: function() { 
      this.render(); 
     }, 
     render: function() { 
      this.$el.html(this.template); 
     } 
    }); 

    var AppRouter = Backbone.Router.extend({ 
     routes: {   
      '': 'homeRoute', 
      'home': 'homeRoute', 
      'about': 'aboutRoute', 
      'cool': 'coolRoute', 
     }, 
     homeRoute: function() { 
      var homeView = new HomeView();   
      $("#content").html(homeView.el); 
     }, 
     aboutRoute: function() { 
      var aboutView = new AboutView();   
      $("#content").html(aboutView.el); 
     }, 
     coolRoute: function() { 
      var coolView = new CoolView();   
      $("#content").html(coolView.el); 
     } 
    }); 

    var appRouter = new AppRouter(); 
    Backbone.history.start(); 

是否有一种方法可以使外部模板在JavaScript之外进行拉动。如果页面非常精细,什么是最佳实践?

这是我的jsfiddle链接。

https://jsfiddle.net/galnova/k4ox8yap/14/

回答

1

如果您正在使用一个javascript模块加载像RequireJs(你可能会发现,当应用程序变得更加复杂,自己做!)然后模板可以使用RequireJs text plugin外部源加载。

例如,你可能有一个文件名为home.js这可能看起来像:

require([ "backbone", "underscore", "text!templates/template.html" ], 
    function(Backbone, _, template) { 

     return Backbone.View.extend({ 
      template: _.template(template), 
      initialize: function() { 
       this.render(); 
      }, 
      render: function() { 
       this.$el.html(this.template); 
      } 
     }); 
    } 
); 

然后一个app.js文件可能包含应用程序的逻辑,需要你的观点:

require([ "backbone", "jquery", "home.js" ], 
     function(Backbone, $, HomeView) { 

      var AppRouter = Backbone.Router.extend({ 
       routes: {   
       '': 'homeRoute', 
       'home': 'homeRoute', 
       // etc 
       }, 
       homeRoute: function() { 
       var homeView = new HomeView();   
       $("#content").html(homeView.el); 
       }, // etc 
2

你可以在你的HTML

<script id='CoolViewTpl' type='template'> 
     <h1>Cool</h1><p>This is the third test. I think this is the way.</p> 
</script> 

然后在你的渲染FUNC指定模板,只需选择由ID模板和获取内容。

var CoolView = Backbone.View.extend({ 
     template: "#CoolViewTpl", 
     initialize: function() { 
      this.render(); 
     }, 
     render: function() { 
      this.$el.html($(this.template).html()); 
     } 
    });