简体   繁体   English

如何访问在挖空中使用$ data映射的对象?

[英]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. 我正在使用敲除属性映射将Subjects对象映射到li元素,如下所示。

<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. 之后,我必须使用JQuery方法访问主题对象。

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

Note: "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. 但是总是将字符串作为[Object Object]而不是真正的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. 只需在可拖动中覆盖“ helper”功能即可。 And then put this data using jQuery if you need: 然后,如果需要,可以使用jQuery放置此数据:

  • ko.dataFor ko.dataFor

  • ko.contextFor ko.contextFor

jsfiddler jsfiddler

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

}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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