我很擅长使用KO。我试图在自定义绑定的init部分中的viewmodel中调用我的一个函数。搜索后我找不到多少帮助。问题是当我在输入字段中点击tab键时出现此错误:TypeError: viewModel.addLine is not a function
。我的另一个问题是,我应该在enterPress
之后提出什么?现在我只是放一个对我没用的随机字符串。
HTML:
<input data-bind="value: retail, valueUpdate: 'afterkeydown', enterPress: 'addRow'" class="form-control" />
KO Viewmodel:
var itemsModel = function(items) {
var self = this;
self.items = ko.observableArray(items);
self.addLine = function() {
self.items.push({
itemNo: "",
brocCode: "",
itemDesc: "",
retail: ""
});
};
self.removeItem = function(item) {
self.items.remove(item);
};
};
自定义绑定功能:
ko.bindingHandlers.enterPress = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var allBindings = allBindingsAccessor();
element.addEventListener('keydown', function (event) {
var keyCode = (event.which ? event.which : event.keyCode);
if (keyCode === 13 || keyCode === 9) {
console.log("hit enter!");
console.log(element);
console.log(valueAccessor);
console.log(allBindingsAccessor);
console.log(viewModel);
viewModel.addLine();
return false;
}
return true;
});
}
};
这两段代码都在$(document).ready(function () {
函数之外。
更新
忘了你们要问的这件作品。以下是在设置HTML后调用的其余代码:
function GetItems() {
var itemsJSON = @Html.Raw(Json.Encode(Model.brochureItems));
var viewModel = new itemsModel(itemsJSON);
ko.applyBindings(viewModel);
}
答案 0 :(得分:0)
您可以绑定任何ViewModel的功能并通过valueAccessor()
访问它,不是吗?
似乎一切正常......
var itemsModel = function(items) {
var self = this;
self.items = ko.observableArray(items);
self.retail = ko.observable("");
self.addItem = function() {
if ("" === self.retail()) return;
self.items.push(self.retail());
self.retail("");
};
self.removeItem = function(item) {
self.items.remove(item);
};
};
ko.bindingHandlers.enterPress = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var allBindings = allBindingsAccessor();
element.addEventListener('keydown', function (event) {
var keyCode = (event.which ? event.which : event.keyCode);
if (keyCode === 13 || keyCode === 9) {
console.log("hit enter!");
// viewModel.addItem();
valueAccessor()();
return false;
}
return true;
});
}
};
ko.applyBindings(new itemsModel([ "Item1", "Item2", "Item3" ]))
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
<input data-bind="value: retail, valueUpdate: 'afterkeydown', enterPress: addItem" class="form-control" />
<ul data-bind="foreach: items">
<li>
<span data-bind="click: $root.removeItem">[x]</span>
<span data-bind="text: $data"></span>
</li>
</ul>
&#13;