Cause an array of events Backbone event:name

2019-02-21 02:50发布

_.extend(object, Backbone.Events);

object.on("myalert:one", function(msg) {
  document.body.innerHTML+=("eve1 " + ' msg:= '+msg+ ' ;name:= '+this.name);
},context);


object.on("myalert:two", function(msg) {
  document.body.innerHTML+=(" eve2 " + ' msg:= '+msg+ ' ;name:= '+this.name);
});

I want сall all events are tied to this object with mask alert:.

   object.trigger("myalert", "param");

1条回答
别忘想泡老子
2楼-- · 2019-02-21 03:18

There isn't any namespacing in Backbone.Events but you could add your own. For example, something like this:

obj.trigger_matching = function(re) {
    var args = [''].concat([].splice.call(arguments, 1));
    for(name in this._events) {
        if(!name.match(re))
            continue;
        args[0] = name;
        this.trigger.apply(this, args);
    }
};

would allow you to say obj.trigger_matching(/^myalert:/, 1, 2, 3) and The Right Thing would happen.

Demo: http://jsfiddle.net/ambiguous/p8p5R/

That will trigger multiple 'all' events (one for each this.trigger.apply) which may or may not be what you want. If it isn't then replace the this.trigger.apply call with a custom version of the standard trigger so that you can trigger at most one 'all' event.

查看更多
登录 后发表回答