为什么 viewmodel 函数代码在加载时执行?
Why is viewmodel function code executing on load?
我的视图模型中有一个函数会在页面加载后立即执行。
我有一个只会显示警报的按钮(目前):
<button type="button" class="btn btn-outline-primary waves-effect waves-light" data-bind="click: $root.showData('user')">POS User</button>
这是我的整个视图模型:
let User = function(id, firstName, lastName, email, phone, isActive ){
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phone = phone;
this.isActive = isActive;
}
function UsersViewModel () {
var self = this; // Scope Trick
// User, Customer, Tech
self.currentUserType =
ko.observable("posUser");
// Arrays
self.posUsers = ko.observableArray();
self.customers = ko.observableArray();
self.technicians = ko.observableArray();
self.currentUsers = ko.observableArray();
self.currentUsers.push(new User(12,"John","Smith","john@gmail.com","800-333-3333",true));
self.showData = function(userType){
alert(userType);
}
};
ko.applyBindings(new UsersViewModel());
看到加载时如何显示警报了吗?
知道为什么会这样吗?
这里有两种方法可以解决您的问题:
将你的函数包装在另一个函数中:
<button data-bind="click: function () { $root.showData('user'); }">POS User</button>
如果你在上下文中,比如with: user
或者在foreach
和$data
中,你可以像下面那样做在您的函数中,第一个参数将是您当前的上下文:
<!-- ko with: user -->
<button data-bind="click: $root.showData">POS User</button>
<!-- /ko -->
self.showData = function (user) { ... };
作为一个有点不相关的评论,你有没有想过你的缩写 'POS' 以及它对很多人来说的全文? :)
我的视图模型中有一个函数会在页面加载后立即执行。
我有一个只会显示警报的按钮(目前):
<button type="button" class="btn btn-outline-primary waves-effect waves-light" data-bind="click: $root.showData('user')">POS User</button>
这是我的整个视图模型:
let User = function(id, firstName, lastName, email, phone, isActive ){
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phone = phone;
this.isActive = isActive;
}
function UsersViewModel () {
var self = this; // Scope Trick
// User, Customer, Tech
self.currentUserType =
ko.observable("posUser");
// Arrays
self.posUsers = ko.observableArray();
self.customers = ko.observableArray();
self.technicians = ko.observableArray();
self.currentUsers = ko.observableArray();
self.currentUsers.push(new User(12,"John","Smith","john@gmail.com","800-333-3333",true));
self.showData = function(userType){
alert(userType);
}
};
ko.applyBindings(new UsersViewModel());
看到加载时如何显示警报了吗?
知道为什么会这样吗?
这里有两种方法可以解决您的问题:
将你的函数包装在另一个函数中:
<button data-bind="click: function () { $root.showData('user'); }">POS User</button>
如果你在上下文中,比如with: user
或者在foreach
和$data
中,你可以像下面那样做在您的函数中,第一个参数将是您当前的上下文:
<!-- ko with: user -->
<button data-bind="click: $root.showData">POS User</button>
<!-- /ko -->
self.showData = function (user) { ... };
作为一个有点不相关的评论,你有没有想过你的缩写 'POS' 以及它对很多人来说的全文? :)