按钮点击创建可拖动的div

时间:2014-09-01 02:37:45

标签: jquery jquery-ui knockout.js

我目前正在将框架knockout.js与jquery ui结合使用(以使div可拖动)。我已经能够硬编码可拖动的div的数量并附加文本= self.items(['One','Two','Three','Four','Five','Six']);。我想让它变得更有活力。如何在按钮单击事件上创建新的div,该事件还会将文本区域附加到新div? JSFIDDLE

Knockout.js

ko.bindingHandlers.draggable={
    init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
        $(element).draggable();
    }
};

ko.bindingHandlers.droppable={
    init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
        $(element).droppable();
    }
};

var vm=function(){
    var self=this;
    self.items=ko.observableArray();
    self.init=function(){
        self.items(['One','Two','Three','Four','Five','Six']);
    }
    self.remove=function(item){
        console.log(item);
        self.items.remove(item);
    }
    self.init();
}

ko.applyBindings(new vm());

HTML

<textarea></textarea>
<button>Generate New Div</button>
<div data-bind="foreach:items">
    <div href="#" class="item" data-bind="draggable:true,droppable:true">
        <span data-bind="click:$parent.remove">[X]</span><br><br>
        <center><span  data-bind="text:$data"></span></center>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

向textarea添加一个可观察的绑定

self.textContent = ko.observable('');

<textarea data-bind="value: textContent"></textarea>

创建一个add函数,将它绑定到按钮并将一个新值推送到observable数组

self.addNew = function() {
  self.items.push( self.textContent() );
  self.textContent('');
}

<button data-bind="click: addNew">Generate New Div</button>