开发者

Using multiple templates and bindings in a single view

开发者 https://www.devze.com 2023-02-09 10:29 出处:网络
I am using KnockoutJS to display a list of images. Say I am using a template X to show this list, and I have defined another template Y to display details in a separate dialog of a selected image. I a

I am using KnockoutJS to display a list of images. Say I am using a template X to show this list, and I have defined another template Y to display details in a separate dialog of a selected image. I am facing issues binding the selected image with this detail template Y. Below is a mock/partial code of my actual view

ViewModel:

var viewModel {
    photos:ko.observableArray(//list of photos),
    showDetails:function(item){
        //show the details of the selected image in dialog
    }
 };

The binding is applied as

 ko.applyBindings(viewModel);

This is how X is defined

<script id="X" type="text/html">
  {{each(i,item) photos()}}
      <a href="javascript:;" data-bind="click:function(){showDetails(item);}">show Image</a>
  {{/each}}开发者_StackOverflow社区
</script>

This is how the template is applied

 <div class="list" data-bind="template: {name:'X'}"></div>

This is a mockup of template Y

 <script id="Y" type="text/html">
   <img src="{url}" />
 </script>

How should I define the showDetails function to apply the bindings to template Y?


Here is a sample that works: http://jsfiddle.net/rniemeyer/MCQgY/.

Easiest way is to define an observable that represents the selected photo. The click binding then just needs to set the observable by calling it like: viewModel.selectedPhoto($data).

Hope this helps. Let me know if you have additional questions/problems with it.

0

精彩评论

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