【问题标题】:MathJax + Knockout.js SubscriptionMathJax + Knockout.js 订阅
【发布时间】:2013-10-11 05:25:35
【问题描述】:

我正在使用 knockout.js 根据 Ajax 调用动态插入值。其中一个值 content.front 是可以包含 MathJax 表达式的 utf8 文本。我试图弄清楚如何让 MathJax 在每次 knockout.js 更新 div 时呈现表达式。我不能让它工作,我不知道为什么。这是 JavaScript:

var ViewModel = function(data) {
  var self = this;
  self = ko.mapping.fromJS(data, {}, self);
  self.content.back.subscribe( function() {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub,"preview-back"]);
  });
}; 

和哈姆雷特:

 <div .wrap>
   <div .tab-content>
     <div .tab-pane #preview-back data-bind="text: content.back">

(这个 Hamlet 渲染的 html 是有效的 html 5...)

就目前而言,knockout.js 正在将文本呈现在适当的 div 中。当我更改文本时,div 也会更改。 MathJax 似乎被触发了——弹出了“100% 排版”的小弹出窗口。但是 div 没有改变。

【问题讨论】:

    标签: knockout.js mathjax


    【解决方案1】:

    好的,所以我最终为淘汰赛制作了自定义绑定。我在这里也使用 jquery:

    ko.bindingHandlers.mathjax = {
      update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        // This will be called once when the binding is first applied to an element,
        // and again whenever the associated observable changes value.
        // Update the DOM element based on the supplied values here.
        var value = valueAccessor(), allBindings = allBindingsAccessor();
    
        var valueUnwrapped = ko.unwrap(value);
        // the replace is an artefact of my encoding.  Maybe I will use markdown instead.
        $(element).html(valueUnwrapped.replace(/\n/g, '<br>'));
        MathJax.Hub.Queue(["Typeset",MathJax.Hub,element]);
      }
    };
    

    ViewModel 保持不变,html 模板为:

         <div data-bind="mathjax: content.back"></div>
    

    希望这对其他人有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 2013-04-25
      • 2014-01-19
      • 1970-01-01
      • 2013-08-01
      • 2020-12-06
      • 1970-01-01
      相关资源
      最近更新 更多