我在一个项目中同时使用Dust.js和Knockout.js,使用一个名为Duster-KO的模块来集成两者。当我尝试在客户端渲染灰尘模板时会出现问题:当我将一个可观察对象或任何包含可观察对象的对象传递给 Context 参数中的dust.render() 时,灰尘实际上将 KO 可观察对象设置为“块”对象。我相信这是因为 Knockout observables 是函数,所以 Dust 认为我传递给它的函数是回调而不是 observable,然后它正在执行并以某种方式设置 observable。
有什么办法可以避免这个问题,或者防止 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 不是一个选项。