非DOM元素的事件侦听器 [英] Event listener on non-DOM elements

查看:229
本文介绍了非DOM元素的事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个MVC框架,现在我正在实现视图模型绑定,我的意思是,当模型更改时,触发刷新/渲染/任何模型。所以,我需要一个对象的事件侦听器:

  model.on(customEvent,appendItem); 

$(#button)。on(click,function(){
model.add(item);
model.trigger(customEvent);
});

function appendItem(item){
$(#content)。append(item.toHTML());
}

那么如何在对象上创建我的事件监听器?

解决方案

如果您已经在使用jQuery,可以使用其内置的事件处理功能。



这是一个有趣的事实,您也可以将任何类型的JavaScript对象放入jQuery集合中,而不仅仅是DOM元素。然后,您可以使用一组有限的jQuery方法( .data() .prop() .on() .off() .trigger() .triggerHandler())。

  //创建模型 - 它可以是任何类型的对象
var model = {};

//传递给jQuery函数,你有一个jQuery集合
//你可以在对象上放置一个事件处理函数
$(model).on('customEvent ',function(){console.log('hehe');});

//并触发它
$(model).trigger('customEvent');




I'm trying to implement a little MVC framework and now I'm implementing the view-model binder, I mean, when the model changes, trigger a refresh/render/whatever on the model. So, I need an event listener on a object:

model.on("customEvent",appendItem);

$("#button").on("click",function(){
    model.add(item);
    model.trigger("customEvent");
});

function appendItem(item) {
   $("#content").append(item.toHTML());
}

So how can I create my event listener on objects?

解决方案

If you are already using jQuery, you can use its built-in event handling facilities.

It's a little known fact that you can also put any kind of Javascript objects into a jQuery collection, not just DOM elements. Then you can use a limited set of jQuery methods (.data(), .prop(), .on(), .off(), .trigger() and .triggerHandler()) on these objects.

//create the model - it can be any kind of object
var model = {};

//pass it to the jQuery function and you have a jQuery collection
//you can put an event handler on the object
$(model).on('customEvent', function () { console.log('hehe'); });

//and trigger it
$(model).trigger('customEvent');

这篇关于非DOM元素的事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆