vnm
August 18, 2016, 1:12pm
1
Hi there!
I have troubles with data context;
Here is my code (unfortunatly, meteorpad is broken)
router.js(I use iron:router)
Router.configure({
layoutTemplate: 'layout'
});
Router.route('home',{
path: '/',
action: function(){
this.redirect('sections', {page: 0});
}
});
Router.route('sections', {
path: '/sections/:page',
data: function(){
var data = {};
data.params = {};
data.params.page = this.params.page?this.params.page:0;
return data;
}
});
template.html
<template name="layout">
{{>yield}}
</template>
<template name="sections">
Page: {{params.page}}
<br>
<a href="{{pathFor 'sections' page=0}}">Page 0</a>
<a href="{{pathFor 'sections' page=1}}">Page 1</a>
<a href="{{pathFor 'sections' page=2}}">Page 2</a>
<br>
<button>what page?</button>
</template>
template.js
Template.sections.onRendered(function(){
let scope = this;
$("button").on("click", function(){
alert("page: " + scope.data.params.page);
});
});
When I click button, button-handler has the scope, which had the template, when rendered, but not actual in this moment;
Instead of setting up event handlers with jQuery, you should be using template events . You can see in the examples how to get the data context.
vnm
August 18, 2016, 1:42pm
3
Of course, this is sipmple case!
In this case I can use template events, but in another cases, i cant, what should i do?
For example, i use rubaxa:sortable package and handle dragEnd (onEnd) event, can I use template events for this purpose? I think, no.
Ah What does Template.currentData()
resolve to?
vnm
August 18, 2016, 3:02pm
5
I can call it from “onRendered” scope, but cant from handler scope.
works:
Template.sections.onRendered(function(){
console.log(Template.currentData());
});
doesnt work:
Template.sections.onRendered(function(){
$("button").on("click", function(){
console.log(Template.currentData());
});
});
error:
view.js:812 Uncaught Error: There is no current view
vnm
August 30, 2016, 10:31am
6
Any ideas? I still use bicycles )
vnm
September 1, 2016, 1:17pm
7
Solved by @user3374348 from stackoverflow.com
thread: http://stackoverflow.com/questions/39271499/template-actual-data-context/39272483#39272483
method Blaze.getData(scope.view) returns actual data context
template.js
Template.sections.onRendered(function(){
let scope = this;
$("button").on("click", function(){
alert("page: " + Blaze.getData(scope.view).params.page);
});
});