如何在Knockout中设置模板绑定URL前缀?

时间:2017-02-08 21:03:10

标签: knockout.js

我有一个包含数百个淘汰模板的用户界面。现在是开发另一个UI的时候了。我需要在模板文件URL的旧引用前加上" uiv1"。例如,无论我说什么

data-bind="name: 'admin/dashboard'" 

我希望它能解决

data-base="name: 'uiv1/admin/dashboard'

在淘汰赛中有没有简单的方法来配置?例如,我可以传递给ko.applyBindings()的一些配置?我没有在源头看到任何东西,但也许还有其他一些我错过的方式。

1 个答案:

答案 0 :(得分:1)

如果可能的话,最好重命名所有实例。

否则,这是一种做法的黑客方式。

var old_template = ko.bindingHandlers['template'];
var prefix = 'uiv1/'

// modifying template binding
ko.bindingHandlers['template'] = {
  'init': function(element, valueAccessor) {
    var bindingValue = ko.utils.unwrapObservable(valueAccessor());
    if (typeof bindingValue === 'string') bindingValue = prefix + bindingValue;
    else if (bindingValue.name) bindingValue.name = prefix + bindingValue.name;
    return old_template.init(element, function() {
      return bindingValue
    });
  },
  'update': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
    return old_template.update(element, valueAccessor, allBindings, viewModel, bindingContext);
  }
}

// view model
var vm = {
  buyer: { name: 'Franklin', credits: 250 },
  seller: { name: 'Mario', credits: 5800 },
  original: { name: 'original', credits: 20000 }
};

ko.applyBindings(vm, document.getElementById('modified'));

//resetting it to original
ko.bindingHandlers['template'] = old_template;

ko.applyBindings(vm, document.getElementById('original'));
body { font-family: monospace; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
<script type="text/html" id="uiv1/admin/dashboard">
  <h3 data-bind="text: name"></h3><span>(from: "uiv1/admin/dashboard")</span>
  <p>Credits: <span data-bind="text: credits"></span>
  </p>
</script>
<script type="text/html" id="dashboard">
  <h3 data-bind="text: name"></h3><span>(from: "dashboard")</span>
  <p>Credits: <span data-bind="text: credits"></span>
  </p>
</script>

<div id="modified">
  Modified Template
  <div data-bind="template: { name: 'admin/dashboard', data: buyer }"></div>
  <div data-bind="template: { name: 'admin/dashboard', data: seller }"></div>
</div>
<hr>
<div id="original">
  Original Template
  <div data-bind="template: { name: 'dashboard', data: original }"></div>
</div>