Backbone.js - how to include an external HTML fragment

时光毁灭记忆、已成空白 提交于 2019-12-13 00:57:50

问题


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>

回答1:


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



来源:https://stackoverflow.com/questions/18053494/backbone-js-how-to-include-an-external-html-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!