gpt4 book ai didi

Javascript MVC + 使用 jQuery 监听和调度事件

转载 作者:行者123 更新时间:2023-11-30 10:44:26 25 4
gpt4 key购买 nike

我正在学习 javascript,对使用 jQuery 监听和调度事件有疑问。

在我的模型中,我有一个触发更改事件的函数:

Model.prototype.setCurrentID = function(currentID) {
this.currentID = currentID;
$('body').trigger('change');
}

触发事件需要一个元素,所以我将它绑定(bind)到“body”。这是好的做法还是坏的做法?

在我更熟悉的 AS3 中,我会简单地从模型中分派(dispatch)一个全局事件,传入一个 const 值,用模型的一个实例监听这个事件:

var model:Model = new Model();
model.addEventListener(CONST_VALUE, handlerFunction);

在 jQuery 中,在我的 View 对象中,我还需要将一个元素附加到监听器,所以我再次将它绑定(bind)到“body”:

var View = function(model, controller) {
var model;
var controller;
this.model = model;
this.controller = controller;

$('body').change(function(evt) { updateSomething(evt); });

function updateSomething(evt){console.log('updating...')};
}

这是有效的,但我对您对这个主题的看法很感兴趣。

最佳答案

我建议使用不公开的私有(private)调度员。
例如,如果用户或插件取消绑定(bind)正文(您的调度程序)上的所有事件,您的逻辑可能会失败:

$('body').unbind();

这可以通过创建一个 dom 节点而不将其暴露给最终用户(不要将其附加到 dom)来避免:

var dispatcher = $('<div />');

Model.prototype.setCurrentID = function(currentID) {
this.currentID = currentID;
dispatcher.trigger('change');
}

var View = function(model, controller) {
this.model = model;
this.controller = controller;

dispatcher.bind('change',function(evt) { updateSomething(evt); });
function updateSomething(evt){console.log('updating...')}
}

使用 jQuery 开发事件编程应用程序时要记住的另一件好事是 jQuery 允许您绑定(bind)/触发自定义事件,还允许您 to namespace your events .这样您就可以更有效地控制事件绑定(bind)和触发:

Model.prototype.setCurrentID = function(currentID) {
this.currentID = currentID;
dispatcher.trigger('modelIdChange.' + this.currentID);
}
Model.prototype.destroy = function() {
// unbind all the event handlers for this particular model
dispatcher.unbind('.'+this.currentID);
}

var View = function(model, controller) {
/*...*/

// this will be triggered for all the changes
dispatcher.bind('modelIdChange',function(evt) { updateSomething(evt); });

// this will be triggered only for the model with the id "id1"
dispatcher.bind('modelIdChange.id1',function(evt) { updateSomething(evt); });

/*...*/
}

关于Javascript MVC + 使用 jQuery 监听和调度事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9242455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com