简体   繁体   中英

How to access the object mapped using $data in knockout?

I am mapping the subjects object to the li element using knockout attribute mapping as given below.

<ul class="nav nav-pills nav-stacked" id="subjects">
    <!-- ko foreach:Subjects -->
    <li data-bind='attr:{"data-event":$data}'>
        <a href="#" data-bind='text:subject_name + " by " + teacher_name;'>
        </a>
    </li>
    <!-- /ko -->
</ul>

After that I have to access the subject object using the JQuery methods.

var originalEventObject = $(element).data('event');

"element" is correctly here. “元素”在此处正确。 The code is inside a loop and don't want to complicate the question by having full code here.

But always getting string as [Object Object] but not real JSON. Please help me on this.

Usually it's not good practice to access data such way. In case of drag & drop it depends is you clone element or not. But you can to this on drag start in case in you use clone. Just override "helper" function in draggable. And then put this data using jQuery if you need:

  • ko.dataFor

  • ko.contextFor

jsfiddler

$(function() {
var model = {
    Subjects: [{text:'first'}, {text: 'second'}]
};
ko.applyBindings(model);
$('#result').text(JSON.stringify(ko.dataFor($('li')[0])));

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM