0
votes

I have a cateogory model which I got using knockout.js mapping plugin, see below

var categoriesViewModel = ko.mapping.fromJS(data);

now this categoriesViewModel has data like

[0]{id=1,name="adventure",description="abc"}

[1]{id=2,name="urban",description="def"}

[2]{id=3,name="romantic",description="ghi"}

I want to bind the data with following html markup

 <section class="categories">

                <ul class="categories-list">
                    <li class="urban"><a  href="javascript:;"><span>urban living</span></a></li>
                    <li class="adventure"><a href="javascript:;"><span>adventure</span></a></li>
                    <li class="romantic"><a href="javascript:;"><span>romantic</span></a></li>
                </ul>
                    <div class="descr">
                        <h3 data-bind="text: name"></h3>
                        <p data-bind="text: Description"></p>
                    </div>
</section>

What I want is that on mouseover on any tag, related description is show in the p tag and name is show in tag.

I can bind the data in javascript using

ko.applyBindings(categoriesViewModel()[0], $('.categories .descr p').get(0));

but here I am using index number like [0], which is kind of hard coded approch so I do not want it like this. what should I do to dynamically bind the data i.e. without specifying index in categoriesViewModel() ?

2

2 Answers

0
votes

Sounds like what you need to do is add a "currentItem" or similar to your view model and then bind your descr div to it (using with). Then you can handle the mouse over on your categories to update the currentItem and it should all update automagically.

Also, why not use foreach binding for you categories?

See if this helps: http://jsfiddle.net/QaYGz/1/

0
votes

This works

<section class="categories">
  <ul class="categories-list" data-bind="foreach: categories">
    <li class="urban"><a href="javascript:;"><span data-bind='text: name, event: { mouseover: function(data, event) { $root.updateDescription($data) }, mouseout: function(data, event) { $root.clearDescription() } }'></span></a></li>                    
  </ul>
  <div class="descr">
    <h3 id="idName" data-bind="text: name"></h3>
    <p id="idDescription" data-bind="text: Description"></p>
  </div>
</section>

var json = {"categories":[{"id":"1","name":"adventure","description":"abc"},
{"id":"2","name":"urban","description":"def"},
{"id":"3","name":"romantic","description":"ghi"}]};

var model = ko.mapping.fromJS(json);

model.updateDescription = function(val) {    
    $("#idName").text(val.name());
    $("#idDescription").text(val.description());
}

model.clearDescription = function() {
    $("#idName").text('');
    $("#idDescription").text('');
}

ko.applyBindings(model);

See also this fiddle for testing.