我是新手,正在尝试构建一个简单的应用程序,在该应用程序中我可以动态添加数据行,但是我不明白为什么在删除data-bind="click: remove" in remove button
时data-bind="click: remove" from remove button
无法正常工作很好,
任何人都可以帮助我解决这一问题,这意味着我如何使用该删除按钮删除动态元素?
感谢进阶:)
function people(name) {
return {
name: ko.observable(name),
remove: function () {
viewModal.peoples.remove(this);
}
};
}
var viewModal = {
self: this,
firstName: ko.observable(),
peoples: ko.observableArray([
{ name: 'Franklin' },
{ name: 'Mario' },
]),
addMore: function () {
this.peoples.push(new people(this.firstName()));
}
};
ko.applyBindings(viewModal);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-6">
<input type="text" data-bind="value:firstName" />
</div>
<div class="col-md-2">
</div>
</div>
<input type="button" value="Add People" data-bind="click:addMore" />
</div>
<div class="col-md-12" data-bind="foreach: peoples">
<div class="row">
<div class="col-md-6 form-group">
<label data-bind="text:name"></label>
<input class="form-control" type="text" />
</div>
<div class="col-md-6 form-group">
<input type="button" class="btn btn-primary" value="remove" data-bind="click: remove" />
</div>
</div>
</div>
</div>
答案 0 :(得分:1)
编辑:正如@GKB在评论中指出的那样,主要错误是最初的人员对象缺少remove
方法,我发现该方法在修复过程中并未真正指出该方法。我的答案...
原始答案:
您不能像尝试那样使用this
。
使用普通对象或new
类实例:
工作示例:
// Example 1: using plain objects
function Person(name, app) {
const self = {
name: ko.observable(name),
remove: () => app.people.remove(self)
};
return self;
}
// Example 2: using `new`
var App = function() {
const self = this;
this.firstName = ko.observable(),
this.people = ko.observableArray(
[ "Franklin", "Mario" ].map(
name => Person(name, self)
)
);
};
App.prototype.addPerson = function() {
this.people.push(Person(this.firstName(), this));
this.firstName("");
};
ko.applyBindings(new App());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-6">
<input type="text" data-bind="value: firstName" />
</div>
<div class="col-md-2">
</div>
</div>
<input type="button" value="Add People" data-bind="click: addPerson" />
</div>
<div class="col-md-12" data-bind="foreach: people">
<div class="row">
<div class="col-md-6 form-group">
<label data-bind="text:name"></label>
<input class="form-control" type="text" data-bind="textInput: name" />
</div>
<div class="col-md-6 form-group">
<input type="button" class="btn btn-primary" value="remove" data-bind="click: remove" />
</div>
</div>
</div>
</div>