所以,一位同事向我介绍了发布/订阅模式(在JS/jQuery中),但是我很难掌握为什么会使用这种模式而不是'普通'的JavaScript/jQuery.
例如,之前我有以下代码......
$container.on('click', '.remove_order', function(event) {
event.preventDefault();
var orders = $(this).parents('form:first').find('div.order');
if (orders.length > 2) {
orders.last().remove();
}
});
Run Code Online (Sandbox Code Playgroud)
我可以看到这样做的优点,例如......
removeOrder = function(orders) {
if (orders.length > 2) {
orders.last().remove();
}
}
$container.on('click', '.remove_order', function(event) {
event.preventDefault();
removeOrder($(this).parents('form:first').find('div.order'));
});
Run Code Online (Sandbox Code Playgroud)
因为它引入了removeOrder为不同事件等重用功能的能力.
但是,为什么你决定实现发布/订阅模式并转到以下长度,如果它做同样的事情?(仅供参考,我使用jQuery tiny pub/sub)
removeOrder = function(e, orders) {
if (orders.length > 2) {
orders.last().remove();
}
}
$.subscribe('iquery/action/remove-order', removeOrder);
$container.on('click', '.remove_order', function(event) {
event.preventDefault();
$.publish('iquery/action/remove-order', $(this).parents('form:first').find('div.order'));
});
Run Code Online (Sandbox Code Playgroud)
我肯定已经读过关于这种模式的内容,但我无法想象为什么这种模式是必要的.我看过的解释如何实现这种模式的教程只是作为我自己的基本示例.
我认为pub/sub的有用性会在更复杂的应用程序中显现出来,但我无法想象.我担心我完全忽略了这一点; 但是如果有的话,我想知道这一点!
你能简洁地解释为什么以及在什么情况下这种模式是有利的?是否值得像上面的例子那样使用pub/sub模式进行代码片段?
我有性能问题.我创建了100个新按钮,我想分配一个Click事件处理程序.我执行此代码大约100次:
Buttons[i].Button.Click += new System.EventHandler(Button_Click);
Run Code Online (Sandbox Code Playgroud)
完成大约需要2秒.我在同一个函数中有很多其他事件赋值,但它们只需要几毫秒来执行.所以我已经改变了我的代码
Buttons[i].Button.MouseUp += new System.Windows.Forms.MouseEventHandler(Button_Click);
Run Code Online (Sandbox Code Playgroud)
现在代码很快(一些毫秒,就像其他代码一样).显然,我已经修改了函数"Button_click"的参数以适应新的事件要求,但没有进行其他更改.
我想知道为什么会发生这种情况.EventHandler会变慢吗?或者我做错了什么?还是有最好的做法?
我正在使用VC2010和C#,在Windows窗体应用程序中使用.NET 4.
编辑:
现在我已经"缩小"了我的代码并将其放在那里:
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Button b;
for(n=0;n<100;n++)
{
b = new Button();
b.Location = new System.Drawing.Point(100, 0);
b.Name = "btnGrid";
b.Size = new System.Drawing.Size(50, 50);
b.Text = b.Name;
b.UseVisualStyleBackColor = true;
b.Visible = false;
b.Text = "..";
b.Click += new EventHandler(this.Button_Click);
//b.MouseUp += new System.Windows.Forms.MouseEventHandler(this.Button_ClickUP);
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
Log(elapsedTime, …Run Code Online (Sandbox Code Playgroud) 我一直在寻求提高我的asp.net页面性能,是否值得将autoeventwireup从true更改为false并添加事件处理程序或性能损失是否很小?
这是一个asp.net 2.0项目.
我正在考虑使用live()将事件处理程序绑定到我尚未插入DOM的函数.然而,这看起来很昂贵 - 必须在插入元素时或任何时候执行"click"元素时进行运行时检查,例如,查看是否应该调用处理程序.
这是在实践中值得担心的事情,还是Javascript如此之快,以至于这不值得关注?
该live()功能的参考页面:http://api.jquery.com/live/
c# ×2
jquery ×2
performance ×2
asp.net ×1
javascript ×1
optimization ×1
runtime ×1
winforms ×1