Backbone.js的 - 如何将外部HTML片段如何将、片段、Backbone、js

2023-09-10 20:43:50 作者:爆菊之交

我在我的文件系统pre-渲染HTML片段。是否有可能在 Backbone.js的加载HTML片段?我在寻找类似的东西 NG-包含的 Angular.js

例如,在我的文件系统(frag.html)

 < H1>我是一个片段LT; / H1>
 

应喷射到模板在给定的占位符位置

 < D​​IV ID =PH>
   &所述;! -  INJECTED  - >
   < H1>我是一个片段LT; / H1>
< / DIV>
 
单元测试Backbone.js应用程序

解决方案

假设,我们有这个占位符:

 < D​​IV ID =PH>< / DIV>
 

和这个HTML中frag.html文件:

 < D​​IV>
    < H1>我< / H1>
    <跨度>一种HTML片段< / SPAN>
< / DIV>
 

让我们定义我们的自定义 prerenderedView 用特殊渲染方法jQuery函数的 负荷 里面:

 窗口。prerenderedView = Backbone.View.extend({
  渲染:函数(){
    这$ el.load(this.options.ajax_template_path,_.bind(this.onRender,本));
    回到这一点;
  },
  的OnRender:函数(){
    //做一些东西在这里,例如
    VAR H1 =该$(H1)。
    VAR文本= this.model.get('some_value');
    的setTimeout(函数(){
      h1.text(文本);
    },2000);
  }
});
 

目前的实例化的时刻 prerenderedView 我们应该通过一个选项 ajax_template_path (这是' frag.html'在我们的例子)。

  $(函数(){
  新的窗口。prerenderedView({
    EL:$('#pH值),
    型号:新Backbone.Model({some_value:这是'}),
    ajax_template_path:frag.html
  })渲染()。
});
 

和,当然,我们不要忘了同源政策如果我们要工作没有一台服务器。例如,我们可以开始用镀铬标志--allow文件存取的档案。

I have pre-rendered HTML fragments in my filesystem. Is it possible to load HTML fragments in backbone.js? I'm looking for something similar to ng-include of Angular.js

for example, in my file system (frag.html)

<h1>I'm a fragment</h1>

Should be injected to the template in a given placeholder location

<div id="ph">
   <!-- INJECTED -->
   <h1>I'm a fragment</h1>
</div>

解决方案

Suppose, we have this placeholder:

<div id="ph"></div>

and this HTML in frag.html file:

<div>
    <h1>I am</h1>
    <span>an HTML fragment</span>
</div>

Let us define our custom PrerenderedView with a special render method with the jQuery function load inside:

window.PrerenderedView = Backbone.View.extend({
  render: function() {
    this.$el.load(this.options.ajax_template_path, _.bind(this.onRender, this));
    return this;
  },
  onRender: function() {
    // do some stuff here, for example
    var h1 = this.$('h1');
    var text = this.model.get('some_value');
    setTimeout(function() {
      h1.text(text);
    }, 2000);
  }
});

At the moment of instantiation of the PrerenderedView we should pass an option ajax_template_path (which is 'frag.html' in our case).

$(function() {
  new window.PrerenderedView({
    el: $('#ph'),
    model: new Backbone.Model({some_value: 'It was'}),
    ajax_template_path: 'frag.html'
  }).render();
});

And, of course, we do not forget about Same Origin Policy if we are going to work without a server. For example, we can start chrome with the flag '--allow-file-access-from-files'.