I read John PAPA's article on JsRender and used its way of loading external HTML files to initialize templates and now I am trying to use JsViews on top of that but it doesn't work as expected !!
I am trying to build a simple menu inside a UL and binding my template to an array of object. One property of this object is whether the menu is selected or not, which should change the style of the text.
Databinding and rendering works, I have added a button to prove that but the use of the "helpers" don't.
I would like to post my code here so I can get some advice on how I started the usage of JsViews and to understand why my helper function is not called.
Content of file: Default.htm
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
.menu{ color: Blue; }
.hover{ color: Red; }
</style>
<script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script src="Scripts/js/jsrender.js" type="text/javascript"></script>
<script src="Scripts/js/jquery.observable.js" type="text/javascript"></script>
<script src="Scripts/js/jquery.views.js" type="text/javascript"></script>
<script src="Scripts/my/my.model.js" type="text/javascript"></script>
<script src="Scripts/my/my.template.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
my.template.loadMenuItemTemplate(onMenuItemAdded);
});
function onMenuItemAdded() {
$.link.menuItemTemplate
(
$("#lstMenu"),
my.model.menuItems
);
}
function Tests() {
my.model.menuItems.push(
{
id: 4,
label: "New",
selected: false
}
);
$.link.menuItemTemplate
(
$("#lstMenu"),
my.model.menuItems
);
}
</script>
</head>
<body>
<ul id="lstMenu" class="menu"></ul>
<button id="test" value="test" onclick="javascript:Tests();">Test !</button>
</body>
</html>
Content of file: _menuItem.tmpl.html
<li data-link="class{:~setClassName()}"><span>{{>label}}</span></li>
Content of file: my.model.js
var my = my || {}; //my namespace
my.model = (function () {
var _menuItems =
[
{
id: 1,
label: "Applications",
selected: false
},
{
id: 2,
label: "Contacts",
selected: true
},
{
id: 3,
label: "Environment",
selected: false
}
];
return {
menuItems: _menuItems
};
})();
Content of file: my.template.js
var my = my || {};
my.template = (function () {
var loadMenuItemTemplate = function (callback) {
if (!($.templates.menuItemTemplate)) {
var file = getTemplateFile("menuItem");
$.when($.get(file))
.done(function (tmplData) {
$.templates(
{
"menuItemTemplate": tmplData,
helpers: { setClassName: my.template.setClassName }
}
);
if (callback != null)
callback();
});
}
},
getTemplateFile = function (name) {
return "../templates/_" + name + ".tmpl.html";
},
setClassName = function () {
return (this.selected) ? "menu hover" : "menu";
};
return {
getTemplateFile: getTemplateFile,
setClassName: setClassName,
loadMenuItemTemplate: loadMenuItemTemplate
};
})();
Thanks for any help, Claude