开发者

Adding widgets to particular div using knockout and jquery templates

Is it possible for a template to check an attribute of an element it is being bound to and then decide if it should actually been bound to it?

The idea is that I would have a number of divs and the template would bind to each div n number of times depending on the id of the div and the id in the data.

<div id="col1" class="col" data-bind="template: 'widgetsTemplate'">  
</div>

<div id="col2" class="col" data-bind="template: 'widgetsTemplate'">    
</div>

@*<div data-bind="template: 'widgetsTemplate'" />*@
<script id="widgetsTemplate" ty开发者_JAVA技巧pe="text/x-jquery-tmpl">
<div>
    {{each(index,widget) widgets}}
        {{if widget.col == cols[index].id}} 
            <div>${widget.name}</div>
        {{/if}}
    {{/each}}
</div>
</script>

Corresponding JS:

var cols = $('.col'); 
function widget(name, col) {
    return {
        name: ko.observable(name),
        col: ko.observable(col)
    };
}
var viewModel = {
    widgets: ko.observableArray(
    [new widget("Widget 1", col1),
    new widget("Widget 2", col2)])
};
ko.applyBindings(viewModel);

This is as far as I got with this idea but I don't seem to be able to progress.

Any ideas would be appreciated.


I know that you can dynamically change which template to bind by looking a result of a function. May be you can change the way of implementing your idea.

In the example code you decide inside the template whatever you want to render. You can decide at top level and choose which template to bind by examining the data. Here is an example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜