非DOM元素上的事件侦听器

gri*_*con 1 javascript jquery events object

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

model.on("customEvent",appendItem);

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

function appendItem(item) {
   $("#content").append(item.toHTML());
}
Run Code Online (Sandbox Code Playgroud)

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

kap*_*apa 5

如果您已经在使用jQuery,则可以使用其内置的事件处理工具.

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

//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');
Run Code Online (Sandbox Code Playgroud)