I have the following code:
HTML:
<ul class="list" data-bind="foreach: list">
<li class="title" data-bind="text:title" contenteditable="true"></li>
<li class="item" data-bind="text:item" contenteditable="true"></li>
</ul>
<button type="button">Save</button>
JS:
var data = {
"list": [{
"title" : "title one",
"item" : "item one"
}]
}
var viewModel=
{
list : ko.observable(data.list)
};
ko.applyBindings(viewModel);
$("button").on("click", function(){
var vm = viewModel;
ko.applyBindings(vm);
var data = ko.toJSON(vm);
console.log(data);
});
However when I do this I get this error:
Uncaught Error: You cannot apply bindings multiple times to the same element.
knockout-3.1.0.js:58
What I would like to do is change the text of one of the items and have it save to the view model when I click the save button.
FIDDLE:
http://jsfiddle.net/sr4Fg/13/
There are few things.
only call applyBindings once, then ko will sync data for you.
you don't need to create a save button, ko sync data automatically.
your title and item are NOT ko.observable, hence ko has no way to auto-update it for you.
ko "text" binding is kind of one way binding, it only updates view when your value changes. You need to use "value" binding in an input tag to get two way binding.
right now, there is no existing ko binding supporting contenteditable. You may build a custom bindingHandler for it, but beware it's tricky to get contenteditable change event.
you list should be an observableArray.
Here is the working example with "value" binding: http://jsfiddle.net/sr4Fg/41/
<ul class="list" data-bind="foreach: list">
<li class="title"><input data-bind="value:title" /></li>
<li class="item"><input data-bind="value:item" /></li>
</ul>
<button type="button">Save</button>
var viewModel=
{
list : ko.observableArray([{
"title" : ko.observable("title one"),
"item" : ko.observable("item one")
}])
};
ko.applyBindings(viewModel);
$("button").on("click", function(){
var data = ko.toJSON(viewModel);
console.log(data);
});
Understand you may load JSON data from ajax call, it's tedious to change all the values into ko.observable. Try http://knockoutjs.com/documentation/plugins-mapping.html if you need.
Related
I am trying to complete some basic add and delete functionality using knockout js.
I am using asp mvc, the knockout mappings plugin and returning a simple list of strings as part of my viewModel
Currently I get three items from the server and the functionality I've created allows me to delete each of those items. I can also add an item. But if I try to delete an item i have added in the KO script I cannot delete it.
After completing research and some tests I guess i'm using the observable's incorrectly. I altered my code to pass ko.observable(""), but that has not worked. What am I doing wrong?
values on load
Array[4]0: "test 1"1: "test 2"2: "test 3"length: 4__proto__: Array[0]
values after clicking add
Array[4]0: "test 1"1: "test 2"2: "test 3"3: c()length: 4__proto__: Array[0]
ko script
var vm = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
this.deleteBulletPoint = function (bulletPoint) {
self.BulletPoints.remove(bulletPoint)
}
this.addEmptyBulletPoint = function () {
self.BulletPoints.push(ko.observable(""));
console.log(self.BulletPoints())
}
}
HTML
<div class="col-lg-6 col-md-6 col-sm-12">
<h4>Bullet Points</h4>
<div id="oneLinedescriptions" class="input_fields_wrap">
<!-- ko foreach: BulletPoints -->
<div class="form-group">
<div class="input-group">
<input type="text" data-bind="value: $data" class="form-control">
<span data-bind="click: $parent.deleteBulletPoint" class="input-group-addon btn">-</span>
</div>
</div>
<!-- /ko -->
</div>
<button id="btnAddDescription" data-bind="click: addEmptyBulletPoint" type="button" class="btn btn-default add_field_button col-lg-12 animate-off">Add New Bullet Point</button>
</div>
EDIT
I have removed $parent but the below error was returned
Uncaught ReferenceError: Unable to process binding "foreach: function (){return BulletPoints }"
Message: Unable to process binding "click: function (){return deleteBulletPoint }"
Message: deleteBulletPoint is not defined
In addition to this I have been able to add new empty elements but they are not updated when a user changes the value. is this because the element I am adding is not observable? And if so how do I get round it?
I've added a snippet to ilustrate how you add and remove using an Observable Array with Knockout, the majority of the code is straight from yours so you are in the right track.
Note that when binding to the methods, in this case, there's no need to reference the $parent as you are not using nested scopes. Also, when adding, you just need to pass in plain text, as the observableArray is expecting an object.
If you work with more complex types, when adding you'll need to pass the object itself, and reference its properties from it inside the scope of the iterator, you can read more about it here.
Hope this helps.
var vm = function (data) {
var self = this;
this.BulletPoints = ko.observableArray(["test1", "test2", "test3"]);
this.deleteBulletPoint = function (bulletPoint) {
self.BulletPoints.remove(bulletPoint)
}
this.addEmptyBulletPoint = function () {
const c = self.BulletPoints().length + 1;
self.BulletPoints.push("test "+c);
}
}
ko.applyBindings(vm);
a {
cursor: pointer;
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<h4>Bullet Points <span><a data-bind="click: addEmptyBulletPoint">Add +</a></span></h4>
<div data-bind="foreach: BulletPoints">
<div class="input-group">
<h3 data-bind="text: $data"></h3>
<a data-bind="click: deleteBulletPoint">Delete</a>
</div>
<div>
The problems you're having are related to the way ko.mapping treats arrays of primitive types. By design only properties that are part of an object get mapped to observables so an array of strings will become an observableArray of strings. It will not become an observableArray of observable strings.
In order to add/remove items from an array where the items themselves are observable you'll have to make your BulletPoints array an array of objects having the string as a property within:
data = { BulletPoints: [{value: "test1"}, {value: "test2"}] }
Here's a working example: jsfiddle
I'm working on a knockout app that now requires routing to be implemented. Grapnel looks like a great solution however I've hit a bit of a brick wall with it.
Knockout click events pass the current 'view model' to whatever function you define in your view - as documented here. As mentioned this is really useful when working with collections and the app I mention uses this quite a lot.
I'm looking for a way of being able to make use of this from within grapnel routes however I'm lost when it comes to a solution.
I've put together a rather simple fiddle to try to help explain things:
https://jsfiddle.net/nt0j49x7/4/
HTML
<div id="app">
<ul class="playlist" data-bind="foreach: albumList">
<li class="album">
<a href="" data-bind="click: $root.showAlbumInfo">
<span data-bind="text: title"></span> -
<strong data-bind="text: artist"></strong>
</a>
</li>
</ul>
<div data-bind="with: selectedAlbum">
<img data-bind="attr:{src: coverImg}" />
<div>
<span data-bind="text: title"></span> - <span data-bind="text: artist"></span>
<a data-bind="attr:{href: spotifyLink}">Listen on spotify</a>
</div>
</div>
</div>
Javascript
var appView = {
albumList: ko.observableArray([
{id: 1, title:'Helioscope' , artist: 'Vessels', coverImg: 'http://ecx.images-amazon.com/images/I/91nC-KVZBBL._SX466_.jpg', spotifyLink: 'https://open.spotify.com/album/3dARFB98TMzKLHwZOgKZhE'},
{id: 2, title:'Dilate' , artist: 'Vessels', coverImg: 'http://ecx.images-amazon.com/images/I/31AvNaBtnpL._SX466_PJautoripBadge,BottomRight,4,-40_OU11__.jpg', spotifyLink: 'https://open.spotify.com/album/7yapNLdtqlYiGFbuEuGRIt'},
{id: 3, title:'White fields and open devices' , artist: 'Vessels', coverImg: 'http://ecx.images-amazon.com/images/I/918vEDkM5PL._SX522_PJautoripBadge,BottomRight,4,-40_OU11__.jpg', spotifyLink: 'https://open.spotify.com/album/4kB1vlgei2DvIweeBoiNVu'}
]),
selectedAlbum: ko.observable(),
showAlbumInfo: function(album, event) {
// knockout supplies the clicked model value as the first parameter
appView.selectedAlbum(album);
}
};
var routes = {
'album/:id' : function(req, event){
// Any ideas on how to pass the 'album' object knockout is
// passing to the appView.showAlbumInfo method into this
// route handler? I can use the ID request param to
// get the model from albumList and set the selectedAlbum
// but that isn't what I'm trying to achieve.
}
};
//var router = new Grapnel(routes);
ko.applyBindings(appView, document.getElementById('app'));
I have been using knockout for year but only took a quick look at Grapnel. I don't see a way of passing objects as parameters. But this is obviously a single page app approach and you have declare your view model as a global. So you can access the "appView" within the router code:
var router = new Grapnel();
//must include the id in the route for function to fire on id change
router.navigate('/album/' + album.id);
console.info(appView.selectedAlbum());
}
);
Then in your viewModel event you can navigate after you set the observable.
showAlbumInfo: function(album, event) {
// knockout supplies the clicked model value as the first parameter
appView.selectedAlbum(album);
router.navigate('/album/' + album.id);
}
fiddle:example
Not sure what your app is going to be but Angular js will do what you are trying to do all in one package with observables and routeing. You won't need knockout.
I have this fallowing list:
<ul data-template="view" data-bind="source: contacts"></ul>
...
<script type="text/x-kendo-template" id="view">
<li>
<div data-role="button" data-bind="click: viewContact">
<h4>#: first_name #</h4>
</div>
</li>
</script>
var someClass = kendo.observable({
title : 'Contact',
contacts : [],
getContacts: function () {
var data = new Contacts().get();
$.when(data()).then(function (data) {
someClass.contacts = data;
});
}
});
I want to assign data from getContacts to products and populate the template with results as they come in.
Any ideas?
In your question you are talking about "products" but in the code snippet i see "contacts".
In any case, you need to do the following:
someClass.set('contacts', data)
Note: assuming you have contacts as a property on the viewmodel.
Since its an observable object, if you don't use get() & set() methods, kendo wont know who all are observing that property. If you use set() method to set new value, Kendo will propagate the change and will notify the listeners of the property.
What I'm trying to achieve:
A form with one text input field(Name), two select fields with some options(Type & Column) with a submit button that creates a Widget with it's title set to Name, data-type set to Type and Column - being it's position in the page.
Type in this case has a couple of different options defined in the view, it works just dandy so I won't go into how I got that working, for now.
As of now I have a page with three columns, each as it's own observableArray - like so:
self.col0 = ko.observableArray([]);
self.col0.id = 'col0'
The same goes for col1 and col2. My goal here is to get the select field to point to these arrays. Atleast that's what I think I need to do.
I have a createWidget function, that looks at the Name and Type values in the DOM (Correct me if I'm wrong here, this is the very first thing I'm creating with KnockOut) and creates a new Widget from that data - like so:
var Widget = function(name, type) {
var self = this;
self.name = name;
self.type = type;
};
var ViewModel = function() {
var self = this;
self.newWidgetName = ko.observable();
self.newType = ko.observable();
// Unrelated code in between
self.createWidget = function(target) {
newName = self.newWidgetName();
newType = self.newType();
widget = new Widget(newName, newType);
target.unshift(widget)
self.newWidgetName("");
};
The input/select elements in the DOM
input.widget-name type="text" placeholder="wName" data-bind="value: newWidgetName"
select data-bind="value: newType"
option value="calendar" Calendar
option value="article" Article
option value="document" Document
select.colPick data-bind="value: colPick"
option value="col0" Column 1
option value="col1" Column 2
option value="col2" Column 3
And my click handler for the createWidget function - like so:
a.btn.create-widget data-bind="click: function(){ createWidget(col0); }"
Shazam, it works!
However, this will only ever output the new Widget into the first col (col0), it won't take the value of the column select field into account and unshift the new widget into the correct column. The errors I'm getting after much trial and error pretty much boils down to:
1) "Cannot call method unshift of undefined"
2) "Uncaught TypeError: Object function observable() .... has no method 'unshift'
So as of right now the code looks like the example above, It's not ideal by any means but with the different columns connected with knockout-sortable, it's not a huge deal if this functionality has to get scrapped. The user can still move the Widgets around from col0 to col2 and vice versa.
If anyone has a resource that would point me in the right direction, or the answer up their sleeve - feel free to share!
All the best, Kas.
Edit: Followup questions for Tyrsius
With the code you supplied I now have the three columns working in the select box, however I am struggling a bit when it comes to outputting the Widgets into view.
With my previous code, this is what the view looked like:
<div class="cols">
<div class="col col-25">
<ul data-bind="sortable: { template: 'widgetTmpl', data: col0, afterMove: $root.widgetData }">
</ul>
</div>
<div class="col col-50">
<ul data-bind="sortable: { template: 'widgetTmpl', data: col1, afterMove: $root.widgetData }">
</ul>
</div>
<div class="col col-25">
<ul data-bind="sortable: { template: 'widgetTmpl', data: col2, afterMove: $root.widgetData }">
</ul>
</div>
</div>
What I'm working with right now is this:
<div data-bind="foreach: columns">
<div data-bind="foreach: items" class="col">
<ul data-bind="sortable: { template: 'widgetTmpl', data: columns, afterMove: $root.widgetData }"></ul>
</div>
</div>
My first question, I realised I wasn't thinking at the time so skip that one.
Question #2: How would I now get these Widgets bound to the col that I picked in the form?
Would I do this?
<ul data-bind="sortable: { template: 'widgetTmpl', data: entryColumn, afterMove: $root.widgetData }"></ul>
Or am I way off? :)
I would keep a collection of the items on the column as a type, which would look like this:
var Column = function(header) {
this.header = ko.observable(header);
this.items = ko.observableArray([]);
};
The trick would be to bind the column select straight to the list of columns on your viewmodel:
<select data-bind="options: columns, optionsText: 'header', value: entryColumn"
Whats happening here is that the actual column object that is selected by the dropdown will be stored in the entryColumn property. Later we can put the item directly into its items list since we will have a reference to it. This also allows us to support any number of columns without changing the logic.
The add code would stay simple:
self.columns = ko.observableArray(columns);
self.entryName = ko.observable('');
self.entryType = ko.observable('');
self.entryColumn = ko.observable('');
self.types = ko.observableArray(['Small', 'Medium', 'Large']);
self.addWidget = function() {
var widget = new Widget(self.entryName(), self.entryType());
//Here is where we can directly add to the selected columns item list
self.entryColumn().items.push(widget);
self.resetForm();
};
Here is the fiddle demonstrating these.
FollowUp Question
You're close, but the data is the items not the EntryColumn
<div data-bind="foreach: columns">
<div data-bind="sortable: { template: 'widgetTmpl', data: items}" class="column">
</div>
</div>
<script type="text/html" id="widgetTmpl">
<p data-bind="text: name() + ' - ' + type()"></p>
</script>
Here is the updated fiddle.
What am I doing wrong? I am trying to create a simple master details view a la the 'canonical MVVM' example.
Here's a simplified example in JSfiddle that doesn't work: http://jsfiddle.net/UJYXg/2/
I would expect to see the name of the selected 'item' in the textbox but instead it says 'observable'?
Here's my offending code:
var list = [ { name: "item 1"} , { name: "Item 2" }];
var viewModel = {
items : ko.observableArray(list),
selectedItem : ko.observable(),
}
viewModel.setItem = function(item) {
viewModel.selectedItem(item);
}
ko.applyBindings(viewModel);
And the HTML
<ul data-bind="foreach: items">
<li>
<button data-bind="click: $root.setItem, text:name"></button>
</li>
</ul>
<p>
<input data-bind="value:selectedItem.name" />
</p>
You are really close. Just need to do value: selectedItem().name or better use the with binding to change your scope. Also, the script that you are referencing is slightly out-of-date (in 2.0 click passes the data as the first arg).
Sample here: http://jsfiddle.net/rniemeyer/acUDH/