1
ko.bindingHandlers.editMode =
{
    update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext)
    {
        var newValueAccessor = ko.utils.unwrapObservable(valueAccessor());
        var $element = $(element);
        var viewModel = new someViewModel();
        $element.append("<input type='text' data-bind='value: model.value' />");
        ko.bindingHandlers.with.update(element, function() { return viewModel }, allBindingsAccessor, viewModel, bindingContext);
    }    
}

someViewModel 是一个视图模型,其中包含model.value我要绑定到附加输入的属性(可观察)。with但是当我为绑定调用更新时Uncaught TypeError: Cannot read property 'savedNodes' of undefined.(knockout.js 调试构建)。我应该如何传递viewModeltowith.update以使其获得与使用时相同的结果data-bind="with: new someViewModel()"?谢谢!

4

1 回答 1

2

with绑定包括一个函数,init其中捕获子元素以用作匿名模板。

我不确定您是否真的在使用传递给绑定的值(valueAccessor)。您希望它在该值更改时更新吗?

否则,一个更简单的模式可能是:

ko.bindingHandlers.mySpecialWith = {
   init: function(element, valueAccessor, all, data, context) {
       var newData = new someViewModel(); //create some new data using what was passed in or however you want

       //manipulate element's children, if necessary    

       ko.applyBindingsToNode(element, { 'with': newData }, context);
   }
};
于 2013-03-18T19:22:08.357 回答