2016-09-13 31 views
1

我想在knockout中使用具有自定义bindingHandler的命名模板,但似乎传入自定义绑定的viewModel被剥离了$ root,$ parent,$的上下文属性组件等,在我的情况下,我需要这个上下文。上下文与自定义绑定中的ko.renderTemplate

当我做ko.renderTemplate上引用$父模板,我得到一个错误 - “的ReferenceError:$父没有定义

注:绑定到对象“鲍勃”只是说明我需要“bob's”$的父母。看来我可以通过做ko.contextFor(元素)获得父视图模型方面,但我需要的 “鲍勃” 对象的背景下...

JAVASCRIPT:

ko.bindingHandlers.test = { 
     init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { 
    }, 
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { 

     var templateId = ko.unwrap(valueAccessor()); 
     console.log(templateId); 
      ko.renderTemplate(templateId, viewModel, {}, element, "replaceChildren"); 
    } 
}; 

var viewModel = function() { 
    this.bob = { 
     name: ko.observable("bob") 
    }; 
    this.numberOfClicks = ko.observable(0); 
    this.registerClick = function(ctx) { 
     console.log(ctx); 
     this.numberOfClicks(this.numberOfClicks() + 1); 
    }; 
}; 

ko.applyBindings(new viewModel()); 

HTML

<div>You've clicked <span data-bind='text: numberOfClicks'>&nbsp;</span> times</div> 
<div data-bind="with:bob"> 
    <span data-bind="test:'testTemplate'"></span> 
</div> 



<script id="testTemplate" type="text/html"> 
<span data-bind="text:name" /> 
<button data-bind="click:$parent.registerClick">CLICK</button> 
</script> 

jsfiddle reproduction here

回答

2

绑定上下文对象是$parent等所在的位置。你应该通过bindingContextko.renderTemplate,而不是viewModel

ko.renderTemplate(templateId, bindingContext, {}, element, "replaceChildren"); 

我这种变化和其他几个更新您的jsfiddle例如,使其工作:https://jsfiddle.net/g462td77/2/