Code_Ed_Student
Code_Ed_Student

Reputation: 1190

Creating draggable div on button click

I am currently using the framework knockout.js in combination with jquery ui(to make the div draggables). I have been able to hard code the number of draggable divs and with text appended = self.items(['One','Two','Three','Four','Five','Six']); . I would like to make it more dynamic. How would I be able to create new divs on a button click event that will also append text a text area to the new 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>

Upvotes: 0

Views: 711

Answers (1)

Robert Slaney
Robert Slaney

Reputation: 3722

Add an observable bound to the textarea

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

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

The create an add function, bind it to the button and push a new value to the observable array

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

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

Upvotes: 1

Related Questions