Kendo UI filterable itemTemplate中方法访问问题(Marionette视图场景)
嘿,这个问题我太熟了!核心原因就是作用域不匹配导致你的test方法找不到,我来给你拆解下并提供解决思路:
问题根源
在你的Marionette View代码里,test函数是定义在createGrid方法内部的,但Kendo Grid渲染itemTemplate时,它的执行上下文并不是createGrid函数的上下文——Kendo会在自己的内部作用域里执行模板代码,所以自然找不到你定义的test方法。而你在DOJO里的示例能正常运行,大概率是因为test函数处于全局作用域,或者和模板的执行上下文处于同一个作用域中。
解决思路(两种靠谱方案)
方案1:把test作为Marionette View的实例方法
把test挂载到View的原型上,这样你可以通过View实例的引用来调用它,避免作用域丢失:
define(function(require) { var MarionetteView = Marionette.View.extend({ // 将test定义为View的实例方法 test: function(text) { return text + 1; }, init: function(){ // 初始化变量 }, createGrid: function(){ // 保存View实例的引用,防止作用域混淆 var self = this; var kendoGrid = $("#grid").kendoGrid({ columns: [ { field: "country", filterable: { multi: true, itemTemplate: function(e) { // 通过self访问View实例的test方法 return "<span><label><span>#= self.test(data.country || data.all) #</span><input type='checkbox' name='" + e.field + "' value='#= data.country#'/></label></span>" } } } ], filterable: true, dataSource: [ { country: "BG" }, { country: "USA" } ] }); } }); return MarionetteView; });
方案2:利用闭包保存test的引用
如果不想把test放到View原型上,也可以在createGrid内部通过闭包让模板访问到test函数:
define(function(require) { var MarionetteView = Marionette.View.extend({ init: function(){ // 初始化变量 }, createGrid: function(){ // 定义test函数,借助闭包让模板能访问到它 var test = function(text) { return text + 1; }; var kendoGrid = $("#grid").kendoGrid({ columns: [ { field: "country", filterable: { multi: true, itemTemplate: function(e) { // 直接调用test,闭包会保留这个函数的引用 return "<span><label><span>#= test(data.country || data.all) #</span><input type='checkbox' name='" + e.field + "' value='#= data.country#'/></label></span>" } } } ], filterable: true, dataSource: [ { country: "BG" }, { country: "USA" } ] }); } }); return MarionetteView; });
额外提示
另外,你原来的itemTemplate代码里有重复的HTML片段(末尾多了一段e.field + "' value='#= data.country#'/></label></span>"),记得要删掉,避免渲染出无效的HTML哦!
内容的提问来源于stack exchange,提问作者Sheetal Chawla
相关产品推荐
相关产品推荐

