问题描述
我有一个用户页面,当页面加载时,我通过Ajax获得了这些用户,我使用foreach
绑定列出了他们,如下所示:
I have an array of users that I get via Ajax when the page loads and I list them using the foreach
binding, like this:
<div data-bind="foreach: { data: usersArr,
afterAdd: showElement,
beforeRemove: fadeRemove }">
我希望列表显示在页面加载时没有 使用afterAdd
对其施加的fadeIn()
效果,并且当我清空usersArr
数组而没有beforeRemove
时消失射击.
I want the list to show up on page load without the fadeIn()
effect I apply to it using afterAdd
and to disappear when I empty the usersArr
array, without beforeRemove
firing.
我只希望在添加新用户或删除现有用户时触发效果.
I only want the effects to fire when adding a new user or deleting an existing one.
有没有办法做到这一点?
Is there a way to achieve this?
推荐答案
一次将所有数据加载到userArr
中,而不是一一推送:
Load all your data at once in your userArr
instead of pushing them one by one:
viewmodel.userArr(receivedArray); //instead of viewmodel.userArr.push(newElement)
编辑
以上操作无效. afterAdd
和beforeRemove
绑定并不关心如何添加/删除元素,无论如何它们都将被调用.
EDIT
The above does not work. The afterAdd
and beforeRemove
bindings do not care how the elements are added/removed, they will be called in any case.
这是一个丑陋的把戏:在视图模型中添加一个allowAnimation
变量,并仅在设置好代码后运行代码(告诉您这是丑陋的):
Here is an ugly trick: add a allowAnimation
variable to your viewmodel and run the code only when it is set (told you it's ugly):
ViewModel.prototype.showElement = function(elem, index, user) {
if (user.allowAnimation) {
if (elem.nodeType === 1) {
$(elem).hide().fadeIn();
user.allowAnimation = false;
}
}
};
ViewModel.prototype.fadeRemove = function(elem, index, user) {
if (user.allowAnimation) {
if (elem.nodeType === 1) $(elem).fadeOut(500, function() {
$(elem).remove();
user.allowAnimation = false;
});
} else {
$(elem).remove();
}
};
ViewModel.prototype.addUser = function() {
this.usersArr.push({name: 'bla', allowAnimation: true});
};
ViewModel.prototype.removeUser = function(user) {
user.allowAnimation = true;
this.usersArr.remove(user);
};
选中此 小提琴
Check this fiddle
这篇关于在某些情况下,忽略foreach afterAdd和beforeRemove的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!