这是我的html:嗨,伙计们,
我是 knockoutjs 世界的新手,但我很想在我的下一个项目中使用它,因为它似乎是一个强大的框架。但是我在理解 knockoutjs 自定义绑定的工作原理时遇到了一些障碍,因为我无法让它在我自己的代码上工作。所以实际上我自己做了一些小实验,如下面的代码:
这是我的 html 文件中的代码:
<form id="form1" runat="server">
<div data-bind="schoolCalendar: student">
</div>
<br />
<input type="button" data-bind="click: change" value="Click"/>
</form>
这是我的 javascript:
var student = function (firstname, lastname, age) {
self = this;
self.firstname = ko.observable(firstname);
self.lastname = ko.observable(lastname);
self.age = ko.observable(age);
}
var model = function (student) {
self = this;
self.student = ko.observable(student);
self.change = function () {
self.student.firstname = "Virna";
self.student.lastname = "Patel";
self.student.age = 27;
};
}
ko.bindingHandlers.schoolCalendar = {
update: function (element, valueAccessor, allBindingsAccessor, viewModel, context) {
var root = $(element);
var value = valueAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
var allBindings = allBindingsAccessor();
var html = "<span id=\"firstname\">Firstname is " + valueUnwrapped.firstname() + "</span><br/>";
html += "<span id=\"lastname\">Lastname is " + valueUnwrapped.lastname() + "</span><br/>";
html += "<span id=\"age\">Age is " + valueUnwrapped.age() + "</span><br/>";
root.append(html);
ko.applyBindingsToNode($("firstname").get(0), valueUnwrapped.firstname());
ko.applyBindingsToNode($("lastname").get(0), valueUnwrapped.lastname());
ko.applyBindingsToNode($("age").get(0), valueUnwrapped.age());
return ko.bindingHandlers.value.init(element, valueAccessor, allBindingsAccessor, viewModel, context);
}
};
$(document).ready(function () {
var m = new model(new student("John", "Hadikusumo", 43));
ko.applyBindings(m);
});
我的问题是:为什么当我单击按钮时,它不会触发 knockoutjs bindingHandler 上的更新事件。我做错了什么 ?