This is a migrated thread and some comments may be shown as answers.

Scope of "this" for column templates

2 Answers 318 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Alan
Top achievements
Rank 1
Alan asked on 14 May 2014, 10:36 PM
Very surprised I couldn't find more information on this. Most grid libraries allow direct js functions for their column renders. In the case of Kendo UI it must be a string template, which is quite limiting. The problem I am currently facing is this:

// Inside my view
config: {
  a: "A",
  b: "B"
},
 
foo: function(data) {
  return this.config[data.config];
},
 
initGrid: function() {
  this.ui.grid.kendoGrid({
    columns: [{ 
      title: "Column A",
      field: "columnA",
      template: "#= this.foo(data) #"
    }]
  });
}

I have no way to access a member method in my template. This is crazy limiting. ANY of the following scenarios would be workable:

// Direct function access
template: this.foo
 
// Set scope of template execution
template: { template: "#= this.foo(data) #", scope: this }
 
// Templates always executed in scope they are defined in
template: "#= this.foo(data) #"  // Just works

The current requirement that only global methods can be called is severe (not to mention a terrible practice). Please advise on how to circumvent this limitation.

2 Answers, 1 is accepted

Sort by
0
Alexander Valchev
Telerik team
answered on 16 May 2014, 11:09 AM
Hi Alan,

By default the context of Kendo template is the global window object. If you want to change the content of a template you can use jQuery proxy.
For example:
template: { template: $.proxy(kendo.template("#= this.foo(data) #"), { foo: "bar" }) }

Actually you can also use direct function access (because kendo.template actually compiles a JavaScript function).

For example:

<div id="grid"></div>
<script>
    var foo = {
        bar: function(data) {
            return data.name + "_format";
        },
        baz: function() {
            $("#grid").kendoGrid({
                dataSource: {data:[{name: "One"}, {name: "Two"}]},
                columns: [
                { field: "name" },
                { template: this.bar }
                ]
            });
        }
    };
 
    foo.baz();
</script>


Regards,
Alexander Valchev
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
0
Alan
Top achievements
Rank 1
answered on 17 May 2014, 04:52 PM
Excellent news! Thanks for the clarification, there is no mention of direct function access in the docs. Would nice to have them updated.
Tags
Grid
Asked by
Alan
Top achievements
Rank 1
Answers by
Alexander Valchev
Telerik team
Alan
Top achievements
Rank 1
Share this question
or