我正在使用这个很棒的编辑器,但我不知道如何将内容绑定(bind)到 knockout :
http://imperavi.com/redactor/
最佳答案
这是一个完成这项工作的双向绑定(bind)处理程序。与此类处理程序一样,update
函数将更改从 VM 传递到 UI 元素(Redactor 元素),init
将更改从 Redactor 传递回 VM。
当我发布此内容时,它是为 Redactor 9 发布的,我现在已经为 Redactor 10 更新了它。
ko.bindingHandlers.redactor = {
init: function(element, valueAccessor) {
var value = valueAccessor();
// We only want Redactor to notify our value of changes if the value
// is an observable (rather than a string, say).
if (ko.isObservable(value)) {
$(element).redactor({
changeCallback: value
});
}
},
update: function(element, valueAccessor) {
// New value, note that Redactor expects the argument passed to 'set'
// to have toString method, which is why we disjoin with ''.
var value = ko.utils.unwrapObservable(valueAccessor()) || '';
// We only call 'set' if the content has changed, as we only need to
// to do so then, and 'set' also resets the cursor position, which
// we don't want happening all the time.
// This code would work with Redactor 9, but no longer works with Redactor 10
//if (value !== $(element).redactor('get')) {
// $(element).redactor('set', value);
//}
// The API method has become 'code.get', and it behaves a bit differently: it
// returns formatted HTML, i.e. with whitespace and EOLs. That means that we
// would update the Redactor content every time the observable changed, which
// was bad. So instead we can use this:
if (value !== $(element).redactor('core.getTextarea').val()) {
$(element).redactor('code.set', value );
}
}
}
如果要使用 Redactor 编辑的内容的 KO observable 是
content
那么你可以这样做:<textarea data-bind="redactor: content"></textarea>
要使上述内容与 Redactor 10 一起使用,您必须进行一些更改。首先,您必须使用“code.set”和“code.get”,而不是简单的“set”和“get”来与 HTML 交互。但是如果你只这样做,你会发现'code.get'返回的HTML
关于knockout.js - 如何 : redactor. js Knockout.js Binder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14761822/