using knockoutjs I want to have forms that allow infinite choices, but I need the form to display so the user knows it exist. I'm ok with starting with 3 forms, so I'd like to initialize empty objects when the page renders. For some reason, when I initialize one object it breaks my code:
function Task(data) {
this.title=ko.observable(data.title);
this.isDone=ko.observable(data.isDone);
}
function TaskListViewModel() {
// Data
var self=this;
self.tasks=ko.observableArray([]);
// self.tasks.push({'title': ''})
self.newTaskText=ko.observable();
self.incompleteTasks=ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(), function(task) {
return !task.isDone()
});
});
// Operations
self.addTask=function() {
self.tasks.push(new Task({
title: this.newTaskText()
}));
self.newTaskText("");
};
self.removeTask=function(task) {
self.tasks.destroy(task)
};
self.incompleteTasks=ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(),
function(task) {
return !task.isDone() && !task._destroy
});
});
self.save=function() {
$.ajax(".", {
data: ko.toJSON({
tasks: self.tasks
}),
type: "post",
contentType: "application/json",
success: function(result) {
alert(result)
}
});
};
// load initial state from server, convert to tasks, then add em to self.tasks
$.getJSON(".", function(allData) {
var mappedTasks=$.map(allData, function(item) {
return new Task(item)
});
self.tasks(mappedTasks);
});
self.tasks.push({'title': ''})
}
ko.applyBindings(new TaskListViewModel());
body { font-family: Helvetica, Arial }
input:not([type]), input[type=text], input[type=password], select { background-color: #FFFFCC; border: 1px solid gray; padding: 2px; }
.codeRunner ul {list-style-type: none; margin: 1em 0; background-color: #cde; padding: 1em; border-radius: 0.5em;}
.codeRunner ul li a { color: Gray; font-size: 90%; text-decoration: none }
.codeRunner ul li a:hover { text-decoration: underline }
.codeRunner input:not([type]), input[type=text] { width: 30em; }
.codeRunner input[disabled] { text-decoration: line-through; border-color: Silver; background-color: Silver; }
.codeRunner textarea { width: 30em; height: 6em; }
.codeRunner form { margin-top: 1em; margin-bottom: 1em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class="codeRunner">
<h3> Stuff </h3>
<div data-bind="foreach: tasks, visible: tasks().length > 0">
<p data-bind="value: title"></p>
</div>
<ul data-bind="foreach: tasks, visible: tasks().length > 0">
<li>
<input data-bind="value: title, disable: isDone" />
Delete
</li>
</ul>
You have <b data-bind="text: incompleteTasks().length"> </b> incomplete task(s)
<span data-bind="visible: incompleteTasks().length == 0"> -it 's beer time!</span>
<form data-bind="submit: addTask"><button type="submit">Add</button></form>
<script>
</script>
</body>
What is the pattern in knockout to initialize safely with this block of JS? Thank you
The reason you're getting an error is because the isDone property in your initial task was not being set. You also already have a Task viewModel, so why not use it to initialize your array? I've just used an IIFE (immediately-Invoked Function Expression) to initialize new tasks by newing up Task in a for loop. You can do this manually or in whichever way you prefer.
Also be aware of your use of the this keyword. See self.addTask in your code.
Im not sure if this is exactly what you're looking for but I assume you'd need a text input to enter newTaskText or am I missing something? Anyway, this seems to work. Hope is answers your question.
function Task(data) {
this.title = ko.observable(data.title);
this.isDone = ko.observable(data.isDone || false);
}
function TaskListViewModel() {
// Data
var self = this;
self.tasks = ko.observableArray([]);
// self.tasks.push({'title': ''})
self.newTaskText = ko.observable();
self.incompleteTasks = ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(), function(task) {
return !task.isDone()
});
});
// Operations
self.addTask = function() {
self.tasks.push(new Task({
title: self.newTaskText(),
isDone: false
}));
self.newTaskText("");
};
self.removeTask = function(task) {
self.tasks.destroy(task)
};
self.incompleteTasks = ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(),
function(task) {
return !task.isDone() && !task._destroy
});
});
(function(numTasks) {
for (var x = 0; x < numTasks; x++) {
self.tasks.push(new Task({
title: ""
}));
}
})(3)
}
ko.applyBindings(new TaskListViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class="codeRunner">
<h3> Stuff </h3>
<input data-bind="textInput: newTaskText" type="text" />
<input data-bind="click: addTask" type="button" value="Add Task" />
<div data-bind="foreach: tasks, visible: tasks().length > 0">
<p data-bind="value: title"></p>
</div>
<ul data-bind="foreach: tasks, visible: tasks().length > 0">
<li>
<input data-bind="value: title, disable: isDone" />
Delete
</li>
</ul>
You have <b data-bind="text: incompleteTasks().length"> </b> incomplete task(s)
<span data-bind="visible: incompleteTasks().length == 0"> -it 's beer time!</span>
<script>
</script>
</body>
Related
I have a program for a makeshift task list that I am working on that should allow a user to enter more than one task by separating the tasks with a comma. I am not sure how I would write a portion of code to allow this function. I am trying to also make the lists themselves separate so if a user needed to delete a task, all the tasks would not be deleted too.
"use strict";
var $ = function(id) { return document.getElementById(id); };
var tasks = [];
var displayTaskList = function() {
var list = "";
// if there are no tasks in tasks array, check storage
if (tasks.length === 0) {
// get tasks from storage or empty string if nothing in storage
var storage = localStorage.getItem("tasks") || "";
// if not empty, convert to array and store in global tasks variable
if (storage.length > 0) { tasks = storage.split("|"); }
}
// if there are tasks in array, sort and create tasks string
if (tasks.length > 0) {
tasks.sort();
list = tasks.join("\n");
}
// display tasks string and set focus on task text box
$("task_list").value = list;
$("task").focus();
};
var addToTaskList = function() {
var task = $("task");
if (task.value === "") {
alert("Please enter a task.");
} else {
// add task to array and local storage
tasks.push(task.value);
localStorage.tasks = tasks.join("|");
// clear task text box and re-display tasks
task.value = "";
displayTaskList();
}
};
var clearTaskList = function() {
tasks.length = 0;
localStorage.tasks = "";
$("task_list").value = "";
$("task").focus();
};
window.onload = function() {
$("add_task").onclick = addToTaskList;
$("clear_tasks").onclick = clearTaskList;
displayTaskList();
};
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 700px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
label {
float: left;
width: 8em;
}
input {
width: 22em;
margin-right: 1em;
margin-bottom: 1em;
}
#tasks {
margin-top: 0;
float: right;
}
<!DOCTYPE html>
<html>
<head>
<title>Ch09 Task Manager</title>
<link type="text/css" rel="stylesheet" href="task_list.css">
<script type="text/javascript" src="task_list.js"></script>
</head>
<body>
<main>
<h1>Task Manager</h1>
<div id="tasks">
<span id="name"> </span>Tasks<br>
<textarea id="task_list" rows="8" cols="50"></textarea>
</div>
<label for="task">Task</label><br>
<input type="text" name="task" id="task"><br>
<input type="button" name="add_task" id="add_task" value="Add Task">
<input type="button" name="clear_tasks" id="clear_tasks" value="Clear Tasks"><br>
<input type="button" name="delete_task" id="delete_task" value="Delete Task">
<input type="button" name="toggle_sort" id="toggle_sort" value="Toggle Sort"><br>
<input type="button" name="set_name" id="set_name" value="Set Name">
<input type="button" name="filter_tasks" id="filter_tasks" value="Filter Tasks"><br>
</main>
</body>
</html>
I found a lot of other stuff that needed fixing, so I did (mostly having to do with how you use jQuery). Works for me locally. Snippet runner doesn't want to do some of this stuff - sorry! Don't know about that.
var tasks = [];
var displayTaskList = function() {
var list = "";
if (tasks.length === 0) { // if there are no tasks in tasks array, check storage
var storage = localStorage.getItem("tasks") || ""; // get tasks from storage or empty string if nothing in storage
if (storage.length > 0) {
tasks = storage.split("|");
} // if not empty, convert to array and store in global tasks variable
}
if (tasks.length > 0) { // if there are tasks in array, sort and create tasks string
tasks.sort();
list = tasks.join("\n");
}
$("#task_list").val(list); // display tasks string and set focus on task text box
$("#task").focus();
};
var addToTaskList = function() {
var task = $("#task").val();
console.log(`entering addtotask list with task value = ${task}`);
if (task === "") {
alert("Please enter a task.");
} else {
if (task.indexOf(',') === -1) {
tasks.push(task); // add task to array and local storage
} else {
const split = task.split(','); // 2 lines for readability
split.forEach(atask => {
tasks.push(atask);
});
}
localStorage.tasks = tasks.join("|");
$("#task").val(""); // clear task text box and re-display tasks
displayTaskList();
}
};
var clearTaskList = function() {
tasks.length = 0;
localStorage.tasks = "";
$("#task_list").val("");
$("#task").focus();
};
window.onload = function() {
$("#add_task").on('click', function() {
addToTaskList();
});
$("#clear_tasks").on('click', function() {
clearTaskList();
});
displayTaskList();
};
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 800px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
label {
float: left;
width: 8em;
}
input {
width: 22em;
margin-right: 1em;
margin-bottom: 1em;
}
#tasks {
margin-top: 0;
float: right;
}
<body>
<main>
<h1>Task Manager</h1>
<div id="tasks">
<span id="name"> </span>Tasks<br>
<textarea id="task_list" rows="8" cols="50"></textarea>
</div>
<label for="task">Task</label><br>
<input type="text" name="task" id="task"><br>
<input type="button" name="add_task" id="add_task" value="Add Task">
<input type="button" name="clear_tasks" id="clear_tasks" value="Clear Tasks"><br>
<input type="button" name="delete_task" id="delete_task" value="Delete Task">
<input type="button" name="toggle_sort" id="toggle_sort" value="Toggle Sort"><br>
<input type="button" name="set_name" id="set_name" value="Set Name">
<input type="button" name="filter_tasks" id="filter_tasks" value="Filter Tasks"><br>
</main>
<script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
</body>
I have a requirement where I have to suggest in the data list and when a user selects any of the datalist options, I have to update other input fields accordingly.
Here is my input field and Datalist code.
<input type="text" v-model="party.name" class="form-control form-control-sm shadow-sm" #input="searchPartyByName()" placeholder="Party name" list="queriedParties"/>
<datalist id="queriedParties">
<option v-for="party in queriedParties">{{party.name}}</option>
</datalist>
Now, what I want is, When a user hits enter or click on specific data list option, I want to update my this input field (Which is by default with data list) but I also want to set other form fields.
I have bound other form fields with my party data object. So, Only if I can update my party data object by any event on datalist option, I will be happy! I want something like this.
<option v-for="party in queriedParties" #click="setParty(party)">{{party.name}}</option>
I already tried the above-given example but it's not working. I also tried with #change but it's not working too!
Is there any way to accomplish this? I checked almost all the articles, jsfiddles and codepens available but none of them solves my issue.
datalist doesn't have events but the input does. You should do the following:
<template>
<input type="text" v-model="party.name" .... />
<datalist id="queriedParties">
<option v-for="party in queriedParties">{{party.name}}</option>
</datalist>
</template>
<script>
export default {
watch: {
party: {
deep: true,
handler (old_party, new_party) {
if (old_party.name !== new_party.name) this.searchPartyByName(new_party.name)
}
}
}
</script>
It seems that your queriedParties is an array of objects. Does it work if you have just an array of strings?
For objects use something along these lines:
<template>
<div class="sourceselection">
<div>
<div class="jumbotron">
<h2><span class="glyphicon glyphicon-list-alt"></span> News List</h2>
<h4>Select News Source</h4>
<input v-model="source" list="newssources-list" v-on:input="sourceChanged"
name="source-selection" id="source-selection" class="form-control"
placeholder="Please specify news source ..."/>
<datalist id="newssources-list">
<option v-for="source in sources" v-bind:value="source.name" v-bind:label="source.name"></option>
</datalist>
<div v-if="deepSource">
<h6>{{deepSource.description}}</h6>
<a v-bind:href="deepSource.url" class="btn btn-primary" target="_blank">Go To {{deepSource.name}} Website</a>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'sourceselection',
data () {
return {
sources: [],
source: '',
deepSource: ''
}
},
methods: {
sourceChanged: function(e) {
console.log("source = "+this.source+" new value = "+e.target.value);
var newSource = e.target.value;
// only action if value is different from current deepSource
if (newSource!= this.deepSource.name) {
for (var i=0; i<this.sources.length; i++) {
if (this.sources[i].name == newSource) {
this.deepSource = this.sources[i];
this.source = this.deepSource.name;
}
}
this.$emit('sourceChanged', this.deepSource.id);
}
}
},
created: function () {
var api = "https://newsapi.org/v1/sources?language=en";
this.axios.get(api).then((response) => {
this.sources = response.data.sources;
});
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
There is no event in datalist, so you can't handle, you'd better write your own list. Here is a example open in codepen:
//pug
#app
.form-group.has-feedback
input.input-search.form-control(type='text', v-model='word', placeholder='Search')
ul#list(v-if='Object.keys(filtered_projects).length > 0')
li(v-for='(value, key) in filtered_projects', #click='gotoProjectPage(key)')
span {{value}}
p {{key}}
span.glyphicon.glyphicon-search.form-control-feedback
/*css*/
body {
margin: 10px;
}
#app {
width: 400px;
}
#list {
font-size: 12px;
list-style: none;
margin: 0;
padding: 5px 0;
background-color: white;
border-radius: 0 0 5px 5px;
border: 1px #ccc solid;
}
#list li {
display: block;
padding: 5px 15px;
}
#list li:hover {
background-color: #ccc;
}
#list li span {
font-weight: 550;
}
#list li p {
margin: 5px 0 0;
}
//js
var app = new Vue({
el: '#app',
data: {
word: '',
projects: {"DataCenterMetro":"TEST1","IFF_Handway":"国际香料","SPH_Handway":"上药控股广东有限公司空调系统","QingTang_GZ":"广州地铁_清塘站","BTE_Handway":"白天鹅宾馆","NSSC_SZ":"深圳地铁_南山书城站","TA0301_Handway":"天安云谷二期"}
},
computed: {
filtered_projects: function () {
var vm = this, result = {};
if (vm.word) {
for(var key in vm.projects) {
if(key.toLowerCase().indexOf(vm.word) != -1 || vm.projects[key].toLowerCase().indexOf(vm.word) != -1)
result[key] = vm.projects[key];
}
}
return result;
}
},
created: function () {
var vm = this;
//TODO get projects
},
methods: {
gotoProjectPage: function (key) {
console.log('/map_login?project=' + key);
//TODO handle
}
},
});
I wanted my search box to search using tags which I have illustrated below with the image. I have tried using bootstrap tags it doesn't work for me.
This is how my search should look like
Check this fiddle:
https://jsfiddle.net/elmacko/hu2yngat/55/
You can change the filter to fit your needs. Also, this can be ofcourse be refined further but it will give you an idea of how it could be done.
angular.module("app", [])
.directive("badgeSearch", function()
{
return {
restrict: "E",
replace: true,
template: `
<div class='badge-search-container'>
<a href='#' ng-click='removeBadge($index)'
class='badge badge-primary search-badge'
ng-repeat='badge in badges track by $index'>{{ badge }}
</a>
<form class='badge-search-form'>
<input class='badge-search-input' type='text'
ng-model='search'>
<button class='btn btn-primary' type='submit'
ng-click='addBadge()'>
Add
</button>
</form>
</div>`,
controller: "badgeSearchController",
scope: {},
link: function(scope, element, attributes)
{
scope.badges = [];
scope.search = "";
if(attributes.ngModel)
{
scope.modelController = element.controller("ngModel");
scope.modelController.$isEmpty = function(value)
{
return !value || value.length === 0;
};
scope.modelController.$render = function()
{
scope.badges = scope.modelController.$viewValue;
};
}
}
};
})
.controller("badgeSearchController", function($scope)
{
$scope.addBadge = function()
{
if($scope.search)
{
$scope.badges.push($scope.search);
$scope.search = "";
}
};
$scope.removeBadge = function(index)
{
$scope.badges.splice(index, 1);
// This will trigger ng-change to fire, even in cases where $setViewValue() would not.
angular.forEach($scope.modelController.$viewChangeListeners, function(listener) {
try {
listener();
} catch (e) {
this.$exceptionHandler(e);
}
});
};
})
.filter("badgeFilter", function()
{
return function(items, badges)
{
if(!badges || !badges.length)
{
return items;
}
return items.filter(function(item)
{
return badges.indexOf(item) != -1;
});
};
})
.controller("mainController", function($scope)
{
$scope.items = [
"first",
"second"
];
$scope.badges = [];
});
html
<div ng-app="app" ng-controller="mainController">
<badge-search ng-model="badges"></badge-search>
<ul class="list-group">
<li ng-repeat="item in items | badgeFilter:badges" class="list-group-item">{{ item }}</li>
</ul>
</div>
css
.badge-search-input
{
height: 100%;
border: 0px;
outline: none;
}
.badge-search-form
{
display: inline-block;
}
.badge-search-container
{
padding-left: 8px;
height: 39px;
margin: 16px;
border: 1px solid black;
border-radius: 0px 4px 4px 0px;
}
.search-badge
{
margin-right: 8px;
}
Use the ngTagsInput directive:
<html>
<head>
<script src="angular.min.js"></script>
<script src="ng-tags-input.min.js"></script>
<link rel="stylesheet" type="text/css" href="ng-tags-input.min.css">
<script>
angular.module('myApp', ['ngTagsInput'])
.controller('MyCtrl', function($scope, $http) {
$scope.tags = [
{ text: 'just' },
{ text: 'some' },
{ text: 'cool' },
{ text: 'tags' }
];
$scope.loadTags = function(query) {
return $http.get('/tags?query=' + query);
};
});
</script>
</head>
<body ng-app="myApp" ng-controller="MyCtrl">
<tags-input ng-model="tags">
<auto-complete source="loadTags($query)"></auto-complete>
</tags-input>
</body>
</html>
link
https://github.com/mbenford/ngTagsInput
I need to measure the width of the UL that contains LI's with an ng-repeat
the first time it works great. however when reloading the data the width comes in as double the real width I believe it is due to angular rendering the new LI's before removing the old LI's
How can I first remove the old LI's before rendering the new ones
P.S. If I put a timeout of 1000 it works fine however I don't wanna wait 1 second every time.
<ul class='ul'>
<li ng-repeat="thing in data.things" class="buyer_li" ng-init="$last && getUlWidth()">
<p>{{thing.detail}}
</li>
</ul>
<button ng-click="reloadData()">Reload</button>
$scope.getUlWidth = function(){
setTimeout(function() {
$scope.ulWidth = document.querySelector('.ul').clientWidth;
}, 0);
}
$scope.reloadData = function(){
//reloadDataFunc;
}
I found the reason why it happens It's because I didn't track the ng-repeat by anything, add =ing a track by $index solved the issue.
See this question and answers Angular ng-repeat causes flickering
I think it maybe your CSS for the layout, not exactly sure. But I'm including a pen that might be able to help.
function exampleController($scope, exampleFactory, $timeout) {
$scope.list = [];
$scope.listContainerWidth = '???';
$scope.refreshList = function() {
$scope.list = [];
$scope.listContainerWidth = '???';
$scope.listContainerWidth = document.querySelector('.ul').clientWidth;
$timeout(function() {
getList();
}, 1000);
};
function getList() {
exampleFactory
.getList()
.then(function(list) {
$scope.list = list;
});
}
getList();
}
function exampleFactory($http) {
var root = 'http://jsonplaceholder.typicode.com';
function getList() {
return $http.get(root + '/comments')
.then(function(resp) {
return resp.data;
});
}
return {
getList: getList
};
}
angular
.module('app', [])
.controller('exampleController', exampleController)
.factory('exampleFactory', exampleFactory);
.container-fluid {
background-color: #1D1F20;
color: #fff;
font-size: 14px;
font-weight: bold;
button {
margin-top: 20%;
}
}
ul li {
list-style: none;
margin: 10px;
}
.child-padding>div {
padding: 2px;
}
.col-md-2 {
position: fixed;
button {
margin-bottom: 10%;
}
}
.circle-bound {
float: left;
text-align: center;
border-radius: 50%;
width: 25%;
background-color: #0bf;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container-fluid" ng-app="app">
<div class="container" ng-controller="exampleController">
<div class="row">
<div class="col-md-2 text-center">
<button class="btn btn-primary" type="button" ng-click="refreshList()">Refresh Comment List</button>
<div class="circle-bound" ng-bind="listContainerWidth"></div>
</div>
<div class="col-md-10 pull-right">
<ul class="ul">
<li ng-repeat="comment in list track by $index">
<div class="child-padding">
<div ng-bind="comment.email"></div>
<div ng-bind="comment.body"></div>
</div>
<div class="pull-right" ng-bind="comment.name"></div>
</li>
</ul>
</div>
</div>
</div>
</div>
I have a React app here that works in many browsers:
<!DOCTYPE html>
<html>
<head>
<title>React! React! React!</title>
<script src="https://unpkg.com/react#15.3.2/dist/react.js"></script>
<script src="https://unpkg.com/react-dom#15.3.2/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<style>
body {
padding: 50px;
background-color: #66CCFF;
font-family: sans-serif;
}
.todoListMain .header input {
padding: 10px;
font-size: 16px;
border: 2px solid #FFF;
}
.todoListMain .header button {
padding: 10px;
font-size: 16px;
margin: 10px;
background-color: #0066FF;
color: #FFF;
border: 2px solid #0066FF;
}
.todoListMain .header button:hover {
background-color: #003399;
border: 2px solid #003399;
cursor: pointer;
}
.todoListMain .theList {
list-style: none;
padding-left: 0;
width: 255px;
}
.todoListMain .theList li {
color: #333;
background-color: rgba(255,255,255,.5);
padding: 15px;
margin-bottom: 15px;
border-radius: 5px;
}
</style>
</head>
<body>
<div id="container">
</div>
<script type="text/babel">
var destination = document.querySelector("#container");
// es6 is working in the browser :)
let y = [1, 3, 6, 15, 39, 88].find(x => x > 39 && x < 90)
var TodoItems = React.createClass({
render: function(){
var todoEntries = this.props.entries;
function createTask(item){
return (
<li key={item.key}>
<span>{item.text}</span>
<a href="" data-id="{item.id}"
className="remove-filter"
onClick={this.props.remove.bind(item)}
>
remove
</a>
</li>
)
}
// var listItems = todoEntries.map(createTask.bind(this));
return (
<ul className="theList">
{this.props.entries.map(createTask.bind(this))}
</ul>
);
}
});
var TodoList = React.createClass({
getInitialState: function(){
return {
items: []
};
},
addItem: function(e) {
var itemArray = this.state.items;
itemArray.push(
{
text: this._inputElement.value,
key: this.state.items.length
}
);
this.setState({
items: itemArray
})
this._inputElement.value = "";
e.preventDefault();
},
// removing items from a list
// https://stackoverflow.com/questions/27817241/how-to-remove-an-item-from-a-list-with-a-click-event-in-reactjs
removeItem: function(item, event){
event.preventDefault();
var items = this.state.items.filter(function(itm){
return item.id !== itm.id;
});
this.setState({ items: items });
},
render: function() {
return (
<div className="todoListMain">
<div className="header">
<form onSubmit={this.addItem}>
<input ref={(a) => this._inputElement = a}
placeholder="enter task" />
<button type="submit">add</button>
</form>
</div>
<TodoItems remove={this.removeItem} entries={this.state.items} />
</div>
);
}
});
ReactDOM.render(
<div>
<TodoList/>
</div>,
destination
);
</script>
</body>
</html>
I have followed how to remove an item from a list with a click event in ReactJS? and it seems to be working, with a few issues.
First, the example references <a href data-..., but this did not work and redirected me to file:///Users/cchilders/tutorials/javascript/react/todo-list/true, where it got true from something it evaluated (true should be the index.html)
Deletion works using href="", but it flashes the page in an ugly manner, and the usual suspects to make an href do nothing don't work...
...if I try href="#" or href="javascript:;" and similar I get
embedded:60 Uncaught TypeError: Cannot read property 'preventDefault' of undefined
Second, I am getting warning
react.js:20478 Warning: bind(): React component methods may only be bound to the component instance. See TodoList
no matter what, for each thing I try.
Third, it is deleting all items in the list on remove, not just 1 item.
How can I make React do this deletion onclick without refreshing the page, and delete 1 item at a time?
There are few things that u need to change, check the jsfiddle for working example, do the changes in ur code accordingly.
*Don't write like this: {this.props.entries.map(createTask.bind(this))}
instead of that just call a method {this.createTask()} from render, that function will return the complete list, n define createTask outside of the render method. like this:
createTask: function(){
return this.props.entries.map(item=>{
return (
<li key={item.key}>
<span>{item.text}</span>
<a href="#" data-id="{item.id}"
className="remove-filter"
onClick={()=>this.props.remove(item)}
>
remove
</a>
</li>
)})
},
*U forgot to give the dead link to href, don't leave it empty define it like this: href="#".
*Don't bind the props remove method with onClick, use it like normal method calling, like this: onClick={()=>this.props.remove(item)}.
Check jsfiddle: https://jsfiddle.net/79eax14s/
Let me know if u need any help in this.