HTML
<div class="notification-container" data-bind="foreach: notificationArray">
<notification params="data: $data"></notification>
</div>
JS - 使用KnockoutJS創建 '通知' 消息的可觀察到的陣列。
appViewModel.notificationArray = ko.observableArray([
{ message : 'Test 1' },
{ message : 'test 2' }
]);
使用淘汰賽創建一個通知組件
ko.components.register('notification', {
viewModel: function(params) {
var data = params.data;
/* set the message to the data.message */
this.message = data.message || null;
/* removes the notification from the array */
this.removeNotification = function() {
appViewModel.notificationArray.remove(data);
};
/* create timer to remove notification after 5s */
/* need to wrap in closure so that inside of the setTimeout it can know about the data object needed to send to the remove() command */
this.timer = function(obj, timeoutLength) {
/* adding return statement per suggestion on Stack Overflow */
return setTimeout(function() {
appViewModel.notificationArray.remove(obj);
}, timeoutLength);
};
this.timer(data, 5000);
/* log will output function structure */
/* clearTimeout will not work */
this.hover = function() {
console.log(this.timer);
clearTimeout(this.timer);
}
},
template: '<div class="notification show-notification" data-bind="event: { mouseover: hover, fastClick: hover }">'
+'<div class="notifications-close clickable right" data-bind="fastClick: removeNotification"><span class="icon icon-x"></span></div>'
+'<div class="notification-text" data-bind="text: message"></div>'
+'</div>'
});
更新,以反映工作液
JS
appViewModel.notificationArray = ko.observableArray([
{ message : 'Test 1' },
{ message : 'test 2' }
]);
ko.components.register('notification', {
viewModel: function(params) {
var data = params.data;
this.message = data.message || null;
this.timer = null;
this.removeNotification = function() {
appViewModel.notificationArray.remove(data);
};
this.timer = (function(self) {
return setTimeout(function() {
self.removeNotification();
}, 5000);
})(this);
this.hover = function() {
clearTimeout(this.timer);
};
this.restart = function() {
this.timer = (function(self) {
return setTimeout(function() {
self.removeNotification();
}, 5000);
})(this);
}
},
template: '<div class="notification show-notification" data-bind="event: { mouseover: hover, fastClick: hover, mouseout: restart }">'
+'<div class="notifications-close clickable right" data-bind="fastClick: removeNotification"><span class="icon icon-x"></span></div>'
+'<div class="notification-text" data-bind="text: message"></div>'
+'</div>'
});
你在哪裏附加懸停處理程序? –