简体   繁体   English

Knockoutjs和Jquery可拖动div

[英]Knockoutjs and Jquery draggable div

I have an observable array that I add or remove elements to. 我有一个可观察的数组,可以向其中添加或删除元素。 The elements are displayed as DIVs. 元素显示为DIV。 I want to make each DIV draggable, however because the DIV is created on the fly I am not sure how to do this. 我想使每个DIV都可拖动,但是由于DIV是动态创建的,因此我不确定如何执行此操作。 I was thinking of using the JQuery live() function, but I need to pass and action, so I dont think this would be the right approach. 我当时在考虑使用JQuery live()函数,但是我需要传递和操作,所以我认为这不是正确的方法。

This is my code: Knockout: 这是我的代码:淘汰赛:

function AssetViewModel() {


var self = this;

self.assets = ko.observableArray([]);

self.addAsset = function(){
    self.assets.push(
        {
            id: "1",
            content: "Hello World",
            type: "Asset"
        }
    );
}
self.removeAsset = function(asset){
    self.assets.remove(asset);
    };
};

HTML: HTML:

<div id="layer1" data-bind="foreach: assets">
<div data-bind="text: content" class="asset"></div>

</div>

Any suggestions would be greatly appreciated! 任何建议将不胜感激!

This is a job for custom bindings . 这是自定义绑定的工作。 The gist is you create your own binding so you markup looks like this: 要点是您创建自己的绑定,因此标记如下所示:

<div data-bind="foreach: assets">
    <div data-bind="draggable: $data">
        <p>More markup</p>
    </div>
</div>

The custom binding would be: 自定义绑定将是:

ko.bindingHandlers.draggable = {
    init: function (element, valueAccessor, allBindingsAccessor, vieModel, bindingContext){
        $(element).draggable();
        return ko.bindingHandlers.with.init.apply(this, arguments);
    }
};

You don't need to return anything but by calling the with binding init function, you create a wrapper binding that performs your logic and and acts like the binding you're returning. 您不需要返回任何内容,而是通过调用with绑定init函数来创建一个包装器绑定,该包装器执行逻辑并像您要返回的绑定一样工作。 It's generally a good place to start when learning custom bindings. 在学习自定义绑定时,通常是一个不错的起点。

尝试阅读下一篇文章- 重新审视observableArrays的拖放,拖放操作,其中包含详细的解释和样本数量。

I'm unsure whether you just want to add sorting within your layer1 div (or dragging and dropping amongst other dom elements.) Regardless of what you want I'd use the Knockout-Sortable plugin ( https://github.com/rniemeyer/knockout-sortable ). 我不确定您是否只想在layer1 div中添加排序(或在其他dom元素之间拖放)。不管您想要什么,我都会使用Knockout-Sortable插件( https://github.com/rniemeyer / knockout-sortable )。

It worked for me on a complex sort, drag and drop solution with Knockout (named templates nested multiple layers.) 它为我提供了使用Knockout(命名模板嵌套多个图层)的复杂分类,拖放解决方案。

Check the JSFiddles at the bottom of that page to get started. 检查该页面底部的JSFiddles以开始使用。

Hope that helps. 希望能有所帮助。

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

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