【问题标题】:Dust.js overwrites Knockout observables on renderDust.js 在渲染时覆盖 Knockout observables
【发布时间】:2012-08-09 14:57:38
【问题描述】:

我在一个项目中同时使用Dust.jsKnockout.js,使用一个名为Duster-KO 的模块将两者集成。当我尝试在客户端渲染灰尘模板时会出现问题:当我将一个可观察对象或任何包含可观察对象的对象传递给 Context 参数中的dust.render() 时,灰尘实际上将 KO 可观察对象设置为“块”对象。我相信这是因为 Knockout 可观察对象是函数,因此 Dust 认为我传递给它的函数是回调而不是可观察对象,然后它会执行它并以某种方式设置可观察对象。

有什么办法可以避免这个问题,或者防止 Dust 接触 observables?

这是我遇到的一个例子:

var guest = exports.guest = function(opts) {
  this.first = ko.observable(opts.first||"")
  this.last = ko.observable(opts.last||"")

  // ... more model code here
}

var table = exports.table = function(opts) {
  // This is an observable array of guest objects
  this.guests = ko.observableArray(opts.guests||[])
  this.template = "tableTemplate"
  this.target = opts.target  // This is whatever DOM element we are injecting the template into

  // ... more model code here

  var self = this

  this.draw = function() {
    // Before we render the Dust template, the guest's first and last name are as they should be

    // this.ctx is a Context object inherited from another parent object, which has the current object pushed onto it
    var rendered = dust.render(self.template, this.ctx)

    // At this point in the code, the guest's first and last name have been set to Chunk objects, rather than their actual first and last names

    self.target.appendChild(rendered)
  }
}

在上面的例子中,在我渲染灰尘模板之前,每个客人的名字和姓氏都是完整的,并且应该是。但是,之后它们被更改为 Chunk 对象。

不幸的是,在有人建议之前,移除 Dust 并仅使用 Knockout 不是一种选择。

【问题讨论】:

    标签: javascript knockout.js dust.js


    【解决方案1】:

    你是否应用了 Duster-Ko 自述文件中提到的 hack ???

    为什么 Dust hack :(

    不愉快的生意,那个。

    Dust 期望任何功能标签都接受一组参数(块、 语境)。我们可以为每个 KO 构建一个防尘包装 观察者,并用这些构建 Dust 上下文,但这似乎是一个 大量不必要的对象创建。

    相反,我们只是破解 Dust 以不正常评估 Observers 会,并以更多的库存标准处理后果 辅助过滤器。

    来源

    这些更改是在您使用的任何灰尘*js 中完成的。

    主要黑客:

    Chunk.prototype.reference = function(elem, context, auto, filters) {
    -  if (typeof elem === "function") {
    +  if (typeof elem === "function" && elem.name != "observable") {
         elem = elem(this, context, null, {auto: auto, filters: filters});`
    

    哦,另外,我们正在手动调用一些 Dust 模板和咳嗽评估 那。要手动调用模板,我们需要传入一个 Dust Chunk 对象,通常我们不会接触到,所以:

    +dust.chunk= Chunk Tis all! Checkout lib/dust-patch.js for a patch 
    

    针对未指定的灰尘源(目前,dust-core-0.3.0.js 是 预期目标)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      • 1970-01-01
      • 2017-12-11
      • 2012-08-14
      • 1970-01-01
      • 2014-01-31
      相关资源
      最近更新 更多